Prove safety offer32: the smallest number arranged in an array

1 Title Description

  Enter a positive integer array, the array of all the numbers arranged in a number spliced ​​together, the splice can print out all numbers smallest one. 3,32,321 input array} {e.g., print the minimum number of three numbers can be arranged to 321,323.

2 ideas and methods

  Due to the digital stitching int, int so there comes to cross-border issues, the topic returned string; mainly developing comparison algorithm to sort the array, return a> b; // (descending) return a <b; ( From small to large). For example, "3" and "123", "3123"> "1233", it returns false.

  If the numbers m, n and mn nm stitched, if mn <nm, then m should be at the front of n, m is less than n we define this case, if mn = nm, we define the m equal to n. Since mn bits and nm must be the same, so their size comparison rule string comparison in accordance with only the size of the can.

3 C ++ core code

 1 class Solution {
 2 public:
 3     static bool cmp(int a,int b)
 4     {
 5         string A=to_string(a)+to_string(b);
 6         string B=to_string(b)+to_string(a);
 7         return A<B;
 8     }
 9     string PrintMinNumber(vector<int> numbers) {
10         int len = numbers.size();
11         if(len==0)
12             return "";
13         sort(numbers.begin(),numbers.end(),cmp);
14         string result="";
15         for(int i=0;i<len;i++)
16         {
17             result+=to_string(numbers[i]);
18         }
19         return result;
20     }
21 };
View Code

Reference material

https://blog.csdn.net/sz793919425/article/details/98208092

Guess you like

Origin www.cnblogs.com/wxwhnu/p/11419855.html