Monday, July 4, 2016

179. Largest Number

This is a sort problem. The key is the comparator, i.e. a should go before b if ab > ba. After sorting, we simply convert the sorted numbers to string and concatenate them together. The only special case is all numbers are 0. In such case, we only need to return 0.

1:  class Solution {  
2:  public:  
3:    string largestNumber(vector<int>& nums) {  
4:      sort(nums.begin(), nums.end(), [](int a, int b) {return to_string(a) + to_string(b) > to_string(b) + to_string(a);});  
5:      string res;  
6:      for (int i : nums) {  
7:        res += to_string(i);  
8:      }  
9:      return res[0] == '0' ? "0" : res;  
10:    }  
11:  };  

No comments:

Post a Comment