Friday, October 16, 2015

Leetcode: Largest Number (sort)

Largest Number
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 be very large, so you need to return a string instead of an integer.

----------------------------------------
----------------------------------------
1. using string type of x+y>y+x to decide the order of x and y. If x+y>y+x is true, x should be put in front; If not, y should be put in front. Here a self made sort function is used. 
2. then concatenate the string together
/////////////////////////////////
//code
class Solution {
public:
       //self made comparison 
       static bool comp(int a, int b){
              string x = to_string(a), y = to_string(b);
              return x + y>y + x;
       }

       string largestNumber(vector<int>& nums) {

              //sort the nums according to above comparison 
              sort(nums.begin(), nums.end(), comp);
              //convert to string
              string res = "";
              for (int i = 0; i<nums.size(); i++){
                   res += to_string(nums[i]);//concatenate the string
              }
              if (res[0] == '0') res = '0';
              return res;
       }

};

No comments:

Post a Comment