Topic:
Enter an array of positive integers, combine all the numbers in the array into a number, and print the smallest of all the numbers that can be stitched together. For example, enter the array {3,32,321}, then print out the minimum number that these three numbers can be ranked as 321323.
Ideas:
1. Full arrangement
Find all the numbers in the array, and then put each of the entire arrangement together to find out the maximum value of the number to spell out.
2. Define a new collation
If the two digital m,n are spliced into MN and nm, if mn<nm, then M should be in front of N, we define at this time m is less than N, if mn=nm, we define M equals N.
You can consider turning numbers into strings, which prevents the overflow of digital stitching, and the concatenation and comparison of strings is easy to implement.
Because the numbers m and N are stitched together to get MN and nm, their bits must be the same, so comparing their sizes is just a matter of comparing the string size.
Code:
#include <iostream> #include <string.h> #include <stdio.h> #include <algorithm>using namespace std;const int g_maxnumberlength=10;char* g_strcombine1=new char[2*g_maxnumberlength+1];char* g_strCombine2=new char[ 2*g_maxnumberlength+1];int Compare (const void* Strnumber1,const void* strNumber2) {char* str1= (char*) strNumber1; char* str2= (char*) strNumber2; sprintf (G_strcombine1, "%s%s", STR1,STR2); sprintf (G_strcombine2, "%s%s", STR2,STR1); Return strcmp (G_STRCOMBINE1,G_STRCOMBINE2);} void Printminnumber (int* numbers,int length) {if (Numbers==null | | length<=0) return; char** Strnumbers=new Char*[length]; for (int i=0;i<length;i++) {strnumbers[i]=new char[g_maxnumberlength+1]; sprintf (Strnumbers[i], "%d", numbers[i]); } qsort (Strnumbers,length,sizeof (char*), compare); for (int i=0;i<length;i++) printf ("%s", Strnumbers[i]); printf ("\ n"); for (int i=0;i<length;i++) delete[] strnumbers[i]; Delete[] Strnumbers;} int main () {int numbers[]={3,32,321}; int length=sizeof (numbers)/sizeof (numbers[0]); Printminnumber (numbers,length); return 0;}
Online test OJ:
http://www.nowcoder.com/books/coding-interviews/8fecd3f8ba334add803bf2a06af1b993?rp=2
AC Code:
Class Solution {public: static bool Compare (int a,int b) { string strnum1=to_string (a); String strnum2=to_string (b); Return (STRNUM1+STRNUM2) < (STRNUM2+STRNUM1); } String Printminnumber (vector<int> numbers) {string result; if (Numbers.empty ()) return result; Sort (Numbers.begin (), numbers.end (), compare); for (unsigned int i=0;i<numbers.size (); i++) result+=to_string (Numbers[i]); return result;} ;
Question 33: Arrange the array into the smallest number