#379 Reorder array to construct the minimum number

来源:互联网 发布:golang 2.0 编辑:程序博客网 时间:2024/05/18 01:55

题目描述:

 This problem is in a contest: Career Fair Warm Up I . Submit your code and see your ranking!

Construct minimum number by reordering a given non-negative integer array. Arrange them such that they form the minimum number.

 Notice

The result may be very large, so you need to return a string instead of an integer.

Example

Given [3, 32, 321], there are 6 possible numbers can be constructed by reordering the array:

3+32+321=3323213+321+32=33213232+3+321=32332132+321+3=323213321+3+32=321332321+32+3=321323

So after reordering, the minimum number is 321323, and return it.

Challenge 

Do it in O(nlogn) time complexity.

题目思路:

这题和#184 largest number一毛一样,需要注意的是sort function里一定要记得加comp这个argument,否则怎么调都不对(因为comp根本没起作用)。

Mycode(AC = 15ms):

class Solution {public:    /**     * @param nums n non-negative integer array     * @return a string     */    string minNumber(vector<int>& nums) {        // Write your code here        auto comp = [](const string& a, const string& b) {            int la = 0, lb = 0;            while (la < a.length() && lb < b.length()) {                if (a[la] < b[lb]) {                    return true;                }                else if (a[la] > b[lb]) {                    return false;                }                la++; lb++;            }                        while (la < a.length()) {                if (a[la] < b[lb - 1]) {                    return true;                }                else if (a[la] > b[lb - 1]) {                    return false;                }                la++;            }                        while (lb < b.length()) {                if (b[lb] < a[la - 1]) {                    return false;                }                else if (b[lb] > a[la - 1]) {                    return true;                }                lb++;            }                        return false;        };                vector<string> str_nums(nums.size(), "");        for (int i = 0; i < nums.size(); i++) {            str_nums[i] = to_string(nums[i]);        }                sort(str_nums.begin(), str_nums.end(), comp);                string ans = "";        for (int i = 0; i < str_nums.size(); i++) {            ans += str_nums[i];        }                while (ans.length() > 1 && ans[0] == '0') {            ans = ans.substr(1);        }                return ans;    }};


0 0