zoukankan      html  css  js  c++  java
  • LeetCode 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.

    好奇怪这题居然没有记录,不过确实再做跟没做过一样,完全想不出来。。。

    class Cmp {
    public:
        bool operator() (const string& a, const string& b) {
            return cmp(a + b, b + a, a.size() + b.size());
        }
        
        bool cmp(const string a, const string b, int len) {
            int pos = 0;
            while (pos < len) {
                if (a[pos] != b[pos]) {
                    return a[pos] < b[pos];
                }
                pos++;
            }
            return false;        
        }
    };
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            vector<string> strnums;
            for (int num : nums) {
                strnums.push_back(num2str(num));
            }
            
            sort(strnums.begin(), strnums.end(), Cmp());
            
            string res;
            int len = strnums.size();
            for (int i=len - 1; i>=0; i--) {
                if (res.size() == 0 && strnums[i][0] == '0') {
                    continue;
                }
                res = res + strnums[i];
            }
            if (res.size() == 0) {
                res = "0";
            }
            return res;
        }
        
        string num2str(int num) {
            char buf[20] = {0};
            sprintf(buf, "%d", num);
            return string(buf);
        }
    };
    
  • 相关阅读:
    LeetCode 121. Best Time to Buy and Sell Stock
    LeetCode 221. Maximal Square
    LeetCode 152. Maximum Product Subarray
    LeetCode 53. Maximum Subarray
    LeetCode 91. Decode Ways
    LeetCode 64. Minimum Path Sum
    LeetCode 264. Ugly Number II
    LeetCode 263. Ugly Number
    LeetCode 50. Pow(x, n)
    LeetCode 279. Perfect Squares
  • 原文地址:https://www.cnblogs.com/lailailai/p/4625517.html
Copyright © 2011-2022 走看看