[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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

Hide Tags
  Sort
 
 
    这题主要的需要考虑排序中的对比判断,对于给定的两个数lft,rgt,误区是直接 lft rgt 判断,根据题目的思路,介意将rgt 接到 lft后面, 与lft 接到 rgt 后面来对比,这样会简单很多,不过这样需要考虑到是否会溢出的问题,题目的验证好像没有对这一问题的严格控制,可以将相接的数值使用 unsigned long int 来存储,这样避免一定情况的溢出。
 
#include <vector>

#include <iostream>

#include <algorithm>

#include <sstream>

using namespace std;



class Solution {

public:

    string largestNumber(vector<int> &num) {

        struct MyCompared

        {

            bool operator ()(int lft,int rgt)

            {

                long unsigned int lidx=1,ridx=1;

                while(lidx!=1000000000)

                    if(lft>=10*lidx)  lidx*=10;

                    else    break;

                while(ridx!=1000000000)

                    if(rgt>=10*ridx)  ridx*=10;

                    else    break;

                lidx*=10;

                ridx*=10;

                return lft*ridx+rgt > rgt*lidx+lft;

            }

        }myCompared;

        if(num.size()==0)   return "";

        sort(num.begin(),num.end(),myCompared);

        ostringstream os;

        if(num[0]==0)   return "0";

        for(int i =0;i<num.size();i++)

            os<<num[i];

        return os.str();

    }

};



int main()

{

    vector<int > num{10,2};

    Solution sol;

    cout<<sol.largestNumber(num)<<endl;

    return 0;

}

 

你可能感兴趣的:(LeetCode)