zoukankan      html  css  js  c++  java
  • 【LeetCode】179. Largest Number

    Description:

      For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

    Analysis:

      The problem can be solved by sorting. It's reallllllllllllllllllllllllllllllllllllllllllly a tallent and brilliant idea to give a compare function like "return s1 + s2 > s2 + s1". Which converts complication to easiness. OMg...

    Code:

    bool cmp(const string &a, const string &b){
        return a + b > b + a;
    }
    class Solution {
    public:
        string int2String(int n){
            string ret = "";
            if(n == 0) return "0";
            while(n){
                ret += '0' + (n % 10);
                n /= 10;
            }
            for(int i = 0; i < ret.length() / 2; i ++)
                swap(ret[i], ret[ret.length() - i - 1]);
            return ret;
        }
    
        string largestNumber(vector<int>& nums) {
            vector<string>rec;
            for(int i = 0; i < nums.size(); i ++){
                string str = int2String(nums[i]);
                rec.push_back(str);
            }
            sort(rec.begin(), rec.end(), cmp);
            string ans = "";
            for(int i = 0; i < rec.size(); i ++){
                ans += rec[i];
            }
            while(ans[0] == '0' && ans.length() > 1){
                return "0";
            }
            return ans;
        }
    };

    Using some new features in c++11:

    1. Anonymous function: lambda used in cmp(compare function)

    2. to_string(int) : returns a string.

    3. auto

    Learn more about those new features about c++11.

        string largestNumber(vector<int>& nums) {
            vector<string>rec;
            for(auto i : nums){
                rec.push_back(to_string(i));
            }
            sort(rec.begin(), rec.end(), [](const string &s1, const string &s2){ return s1 + s2 > s2 + s1;});
            string ans = "";
            for(auto s : rec){
                ans += s;
            }
            while(ans[0] == '0' && ans.length() > 1){
                return "0";
            }
            return ans;
        }

      

  • 相关阅读:
    while 循环及 break,continue语句
    Binary Search Tree BST Template
    Largest Rectangle in Histogram 解答
    Increasing/ Decreasing Stack
    Stack
    Queue
    Find the largest multiple of 3 解答
    Check whether a given Binary Tree is Complete or not 解答
    Sliding Window Maximum 解答
    Wiggle Sort 解答
  • 原文地址:https://www.cnblogs.com/luntai/p/5767647.html
Copyright © 2011-2022 走看看