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

    C++代码实现:

    #include<iostream>
    #include<string>
    #include<vector>
    using namespace std;
    
    class Solution {
    public:
        string largestNumber(vector<int> &num) {
            if(num.empty())
                return "";
            string ret;
            int i,j;
            while(!num.empty())
            {
                i=0;
                for(j=1;j<(int)num.size();j++)
                {
                    if((to_string(num[i])+to_string(num[j]))<(to_string(num[j])+to_string(num[i])))
                        i=j;
                }
                ret+=to_string(num[i]);
                num.erase(num.begin()+i);
            }
            while(ret.size()>1&&ret[0]=='0')
                ret.erase(ret.begin());
            return ret;
        }
    };
    
    int main()
    {
        Solution s;
        vector<int> vec={3,30,34,5,9};
        cout<<s.largestNumber(vec)<<endl;
    }

    直接调用STL算法进行排序:

    #include<iostream>
    #include<vector>
    #include<string>
    #include<algorithm>
    using namespace std;
    //不能声明non-static成员函数
    bool Mycmp(int n1,int n2)
    {
        string s1=to_string(n1);
        string s2=to_string(n2);
        return s1+s2>s2+s1;
    }
    class Solution
    {
    public:
        string largestNumber(vector<int> &num)
        {
            if(num.empty())
                return "";
            string ret="";
            sort(num.begin(),num.end(),Mycmp);
    //sort(num.begin(),num.end(),[](int n1,int n2){ return to_string(n1)+to_string(n2)>to_string(n2)+to_string(n1);});
            if(num[0]==0)
                return "0";
            for(auto a:num)
                ret+=to_string(a);
            return ret;
        }
    //声明为static成员是可以的
    static bool Mycmp(int n1,int n2)
    {
        string s1=to_string(n1);
        string s2=to_string(n2);
        return s1+s2>s2+s1;
    }
    }; 
    int main()
    {
      Solution s;
      vector<int> num= {3,32,321};
      cout<<s.largestNumber(num)<<endl;
    }

      

  • 相关阅读:
    PHP的命令行脚本调用
    JAVA使用jar命令制作可执行GUI程序
    PHP的代理模式
    PHP中的__clone()
    PHP使用反射动态加载第三方类
    NAT小记
    JAVA睡眠理发师代码记录
    PHP通过反射获得类源码
    PHP中单引号双引号的区别
    [转载]PHP导出数据库数据字典脚本
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4232933.html
Copyright © 2011-2022 走看看