Problem: https://leetcode.com/problems/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.

 

Thought:

1. turn all int into str, then compare next_now+numStr[i] and numStr[i] + next_now to find the next_now, next_now is the next one to append to the result string, this method is O(n2), only beats 5% cpp submissions

2.sort the numStr with a function, the append them one by one    reference: https://discuss.leetcode.com/topic/7286/a-simple-c-solution/2

 

Code C++ thought 1:

class Solution {
public:
    string largestNumber(vector<int>& nums) {
        vector<string> numStr;
        for (int i = 0; i < nums.size(); i++) {
            numStr.push_back(to_string(nums[i]));
        }
        
        string solve = "";
        while (numStr.size() > 1) {
            vector<string>::iterator next = findNext(numStr);
            solve += *next;
            numStr.erase(next);
        }
        solve += numStr[0];
        
        if (solve[0] == '0') {
            return "0";
        }
        return solve;
    }
    
    vector<string>::iterator findNext(vector<string>& nums) {
        int next = 0;
        for (int i = 1; i < nums.size(); i++) {
            string a,b;
            a = nums[next] + nums[i];
            b = nums[i] + nums[next];
            next = a > b ? next : i;
            if (a == b) {
                next = nums[next].length() <= nums[i].length() ? next : i;
            }
        }
        return nums.begin() + next;
    }

};

 

Code C++ thought 2:

class Solution {
public:
    string largestNumber(vector<int> &num) {
        vector<string> numStr;
        for (int i = 0; i < num.size(); i++) {
            numStr.push_back(to_string(num[i]));
        }
        
        string solve = "";
        sort(numStr.begin(), numStr.end(), [](string &s1, string &s2){return s1 + s2 > s2 + s1;});
        for (int i = 0; i < numStr.size(); i++) {
            solve += numStr[i];
        }
        if (solve[0] == '0') {
            return "0";
        }
        
        return solve;
    }
};

 

posted on 2016-07-16 13:23  gavinXing  阅读(184)  评论(0编辑  收藏  举报