zoukankan      html  css  js  c++  java
  • Largest Number

    Total Accepted: 35377 Total Submissions: 202492 Difficulty: Medium

    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.

    关键在于定义一种新的字符串比较规则,使得我们把排序好的字符串数组串一遍就能得到结果。

    新的比较规则是return  s1+s2 < s2+s1;

    然后证明这种比较规则为什么是对的。

    证明:
    假设按这种规则排序好的数组是:A1,A2,A3...Ax....Ay.....An

    根据这种排序规则,最后的排序结果是An...AyAy-1...Ax...A3A2A1

    反证法证明:

    假设存在一个An...AxAy-1...Ay...A3A2A1 > An...AyAy-1...Ax...A3A2A1

    由于Ax<Ax+1<Ax+2<Ax+3<....<Ay-1<Ay 

    那么An...Ay Ay-1... Ax+2 Ax+1 Ax...A3 A2 A1 > An...AyAy-1...Ax Ax+1...A3A2A1,这是根据比较规则来的,比较规则中,若Ax<Ax+1则AxAx+1 < Ax+1Ax

    同样An...AyAy-1...Ax Ax+1...A3A2A1 > An...AyAy-1...Ax Ax+2 Ax+1...A3A2A1>...>An...Ax Ay Ay-1...Ax+2 Ax+1...A3A2A1。

    同理可以证明An...Ax Ay Ay-1...Ax+2 Ax+1...A3A2A1>An...Ax Ay-1...Ax+1 Ay...A3A2A1。

    这就与假设相反,所以得证

    bool comp(const string& lhs,const string& rhs){
        return lhs+rhs < rhs+lhs;
    }
    class Solution {
    public:
        string largestNumber(vector<int>& nums) {
            vector<string> str_nums;
            //以下三种整数转字符串
            /*1.
            for(auto num:nums){
                char buf[20]={0};
                sprintf(buf,"%d",num);
                str_nums.push_back(string(buf));
            }
            */
            /*2.
            vector<string> str_nums(nums.size());
            stringsteam stream;
            for(auto num:nums){
                stream<<num;
                stream>>str_nums[i];
                str_nums.push_back(string(buf));
            }
            */
            for(auto num:nums){
                str_nums.push_back(to_string(num));
            }
            sort(str_nums.begin(),str_nums.end(),comp);
            string res;
            for(int i=str_nums.size()-1;i>=0;i--){
                res.append(str_nums[i].begin(),str_nums[i].end());
            }
            return (res.empty() || res[0]!='0' )?  res : "0";
        }
    };
  • 相关阅读:
    python中selenium+unittest实操
    python+selenium元素定位04——浏览器多窗口处理
    python+selenium元素定位03——自动化常见场景处理
    python+selenium元素定位02——层级定位
    requests.post() 方法的使用
    python+selenium元素定位01——显式、隐式等待
    python+selenium之元素识别二
    IO流常用基类
    STS中导入Jmeter源码遇到的坑
    MySql处理日期时间常用函数
  • 原文地址:https://www.cnblogs.com/zengzy/p/5047263.html
Copyright © 2011-2022 走看看