Largest number
2015.1.23 20:24
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.
Solution:
Sort the numbers and piece them together, you'll get the answer, either largest or smallest. As for what to sort them, please see the comparator ().
Time complexity is O (n * log (n)), space complexity are the same, or less.
Accepted Code:
1 //#define ZZ2#include <algorithm>3#include <cstdio>4#include <iostream>5#include <string>6#include <vector>7 using namespacestd;8 9 BOOLComparatorConst string&S1,Const string&S2)Ten { One stringS12, S21; A -S12 = S1 +S2; -S21 = s2 +S1; the - BOOLres = S12 <S21; - s12.clear (); - s21.clear (); + - returnRes; + } A at classSolution { - Public: - stringLargestnumber (vector<int> &num) { - Chars[ -]; -vector<string>vs; - in intn, I; - ton = (int) num.size (); + for(i =0; I < n; ++i) { -sprintf (s),"%d", Num[i]); theVs.push_back (string(s)); * } $ Panax Notoginseng sort (Vs.begin (), Vs.end (), comparator); - stringres =""; the + for(i = n-1; I >=0; --i) { ARes + =Vs[i]; the } + vs.clear (); - $i =0; $n = (int) res.length (); - while(I < n-1&& Res[i] = ='0') { -++i; the } -res = RES.SUBSTR (i, N-i);Wuyi the returnRes; - } Wu }; - About #ifdef ZZ $ intMain () - { -vector<int>num; - intN; A inti; + solution Sol; the - while(Cin >>N) { $ num.resize (n); the for(i =0; I < n; ++i) { theCIN >>Num[i]; the } thecout << sol.largestnumber (num) <<Endl; - num.clear (); in } the the return 0; About } the #endif
Leetcode-largest number