Title Description
Given a list of non negative integers, arrange them such that they form the largest number.
Subject to the effect
Given a non-zero integer array, the array of numbers in a certain order in accordance with a maximum number of composition.
Examples
E1
Input: [10,2]
Output: "210"
E2
Input: [3,30,34,5,9]
Output: "9534330"
Problem-solving ideas
A simple method, according to certain rules to sort the array, then the array while traversing obtain results.
The rule is: return (a + b), and (b + a) of the larger value.
(PS: a, b are string type)
Complexity Analysis
Time complexity: O (nlog (n))
Space complexity: O (n)
Code
// size comparison rule BOOL CMP ( String A, String B) { return (A + B)> (B + A); } class Solution { public : String largestNumber (Vector < int > & the nums) { Vector < String > Sn ; // the int string into storage for ( int I: the nums) sn.push_back (the to_string (I)); // the string array sorting Sort (sn.begin (), sn.end (), CMP); string = ANS "" ; for ( int I = 0 ; I <sn.size (); I ++ ) ANS + = Sn [I]; // The results head '0' to delete the while ! (ans.size () = . 1 && ANS [ 0 ] == ' 0 ' ) ans.erase ( 0 , . 1 ); return ANS; } };