Original title Address:
https://oj.leetcode.com/problems/largest-number/
Topic content:
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9] , the largest formed number is 9534330 .
Note:the result May is very large, so you need to return a string instead of an integer.
Method:
Very simple.
0. Define the size of two integers: there are integers a and B, if AB > BA, then a > B
1. Call sort, passing in the redefined comparison function, sorted by descending order.
2. Starting with 0, each integer is converted to a string and push to the end of the result string. The resulting string is, of course, initialized to 0.
Here's a little bit of a comparison of the size of two integers. A = 9,b = 12 This is not the case, assuming that the length of a is less than B, and if the first half of A and B are exactly the same, what is the size of a and B treated? For example A = a, B = 128, and a = 9,b = 912 case.
It is advisable to set B and a for unequal portions to C, then the first case C = 8, and the second case C = 12. So actually b = Ac,ab = AAC, BA = ACA. It is easy to see that the head of AB and Ba is definitely a, the key is AC large or CA large. If the AC is large, then a is greater than B, and if the CA is large, B is greater than a.
Of course, you can simply and rudely connect AB and BA, from the angle of the string to see who is big. I haven't tried this, I don't know if it will be tle. Unfortunately, because of the overflow problem, it cannot be represented by integers, only strings.
Lessons learned:
Start always out of RE, the problem is actually the sort function: The incoming compare method can not be returned to a < B and B < A true, that is, can not write a statement similar to return A <= B, or sort will read some messy memory area, and then hang up
All code:
Class Solution {public://define x < Y. When x < Y return true. static bool Compare (int x,int y) {String a = Strval (x); String B = Strval (y); int length = A.size () > B.size ()? B.size (): A.size (); for (int i = 0; i < length; i + +) {if (A[i]! = B[i]) {return a[i]-b[i] > 0; }} return A.size () < B.size ()? (B.compare (B.substr (A.size ()) + B.SUBSTR (0,a.size ())) > 0 true:false): (A.C Ompare (A.substr (B.size ()) + A.SUBSTR (0,b.size ())) < 0? True:false); } string Largestnumber (Vector<int> &num) {sort (Num.begin (), num.end (), compare); if (num[0] = = 0) {return "0"; } string result = ""; for (int i = 0; i < num.size (); i + +) {result + = Strval (Num[i]); } return result; } static string strval (int num) {char tmp[20]; Char index = 0; while (num >=) {Tmp[index + +] = (char) (num% 10 + ' 0 '); Num/= 10; } Tmp[index] = (char) (num + ' 0 '); string res = ""; for (int i = index; I >= 0; I-) {res = res + tmp[i]; } return res; }};
"Original" Leetcodeoj---largest number problem solving report