码迷,mamicode.com
首页 > 其他好文 > 详细

179. Largest Number

时间:2020-04-04 22:44:47      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:bool   empty   ==   result   not   for   form   sage   lang   

Problem:

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

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

思路

Solution (C++):

string largestNumber(vector<int>& nums) {
        if (nums.empty())  return "";
    int n = nums.size();
    string ans = "";
    bool flag = false;
    for (int i = 0; i < n; ++i) {
        if (nums[i]) { flag = true; break; }
    }
    shell_sort(nums);
    if (flag) {
        for (int i = n-1; i >= 0; --i) {
            ans += to_string(nums[i]);
        }            
    } else return "0";

    return ans;
}
int max_bit(int x) {
    int count = 0;
    if (x == 0)  return 1;
    while (x) {
        count++;
        x /= 10;
    }
    return count;
}
bool is_bigger(int x, int y) {
    int x_bit = max_bit(x), y_bit = max_bit(y);
    if (x_bit == y_bit)  return x >= y;
    vector<int> v1 = get_bit(x), v2 = get_bit(y);
    for (auto x : v2)  v1.push_back(x);
    for (auto x : v1)  v2.push_back(x);
    int n = v1.size();
    for (int i = 0; i < n; ++i) {
        if (v1[i] > v2[i])  return true;
        if (v1[i] < v2[i])  return false;
    }
    return true;
}
vector<int> get_bit(int x) {
    vector<int> v;
    if (x == 0)  v.push_back(x);
    while (x) {
        v.push_back(x%10);
        x /= 10;
    }
    for (int i = 0; i < v.size()/2; ++i) {
        swap(v[i], v[v.size()-1-i]);
    }
    return v;
}
void shell_sort(vector<int>& v) {
    int h = 1, n = v.size();
    while (h < n / 3) {
        h = 3 * h + 1;
    }
    while (h >= 1) {
        for (int i = h; i < n; ++i) {
            for (int j = i; j >= h && !is_bigger(v[j], v[j-h]); j -= h) {
                swap(v[j], v[j-h]);
            }
        }
        h /= 3;
    }
}

性能

Runtime: 12 ms??Memory Usage: 7.8 MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB

179. Largest Number

标签:bool   empty   ==   result   not   for   form   sage   lang   

原文地址:https://www.cnblogs.com/dysjtu1995/p/12634610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!