【LeetCode】179. Largest Number
Description:
For example, given [3, 30, 34, 5, 9]
, the largest formed number is 9534330
.
Analysis:
The problem can be solved by sorting. It's reallllllllllllllllllllllllllllllllllllllllllly a tallent and brilliant idea to give a compare function like "return s1 + s2 > s2 + s1". Which converts complication to easiness. OMg...
Code:
bool cmp(const string &a, const string &b){ return a + b > b + a; } class Solution { public: string int2String(int n){ string ret = ""; if(n == 0) return "0"; while(n){ ret += '0' + (n % 10); n /= 10; } for(int i = 0; i < ret.length() / 2; i ++) swap(ret[i], ret[ret.length() - i - 1]); return ret; } string largestNumber(vector<int>& nums) { vector<string>rec; for(int i = 0; i < nums.size(); i ++){ string str = int2String(nums[i]); rec.push_back(str); } sort(rec.begin(), rec.end(), cmp); string ans = ""; for(int i = 0; i < rec.size(); i ++){ ans += rec[i]; } while(ans[0] == '0' && ans.length() > 1){ return "0"; } return ans; } };
Using some new features in c++11:
1. Anonymous function: lambda used in cmp(compare function)
2. to_string(int) : returns a string.
3. auto
Learn more about those new features about c++11.
string largestNumber(vector<int>& nums) { vector<string>rec; for(auto i : nums){ rec.push_back(to_string(i)); } sort(rec.begin(), rec.end(), [](const string &s1, const string &s2){ return s1 + s2 > s2 + s1;}); string ans = ""; for(auto s : rec){ ans += s; } while(ans[0] == '0' && ans.length() > 1){ return "0"; } return ans; }