179. Largest Number

来源:互联网 发布:java接口怎么写 编辑:程序博客网 时间:2024/06/07 23:15

description:

 179

Largest Number   
 22.9%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 is9534330.

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.

my solution:

bool myfunction(int i, int j) {char x[100];char y[100];sprintf(x, "%d", i);sprintf(y, "%d", j);string X = x;string Y = y;if (X + Y > Y + X) return true;else return false;}class Solution {public:string largestNumber(vector<int>& nums) {char temp[100];string result;sort(nums.begin(), nums.end(), myfunction);for(int i=0;i<nums.size();i++) {            sprintf(temp,"%d",nums[i]);            result+=temp;        }        if (nums[0] == 0)result = "0";return result;}};
thought:

首先对所有数字进行排序,排序的规则是(x和y,如果xy组合大于yx组合,则x>y),然后就可以从头到尾把元素组合在一起得到结果。

重点是要想到,这道题考察的是一种排序,一开始我没找到方向,无从下手,后来发现制定规则后,无论数字长度为多少,只要他在规则中是大于别的元素的就放在最前面。

没考虑到的地方是对0值的处理,也算是程序健壮性和维护的一部分,这方面我一直比较弱。

别的有待改进的地方就是,对于C++轮子的应用,to_string函数之前没想到,用的sprint,还要用char*与string进行转换,可以说是很麻烦了。

Better ways:

byisaac7

class Solution {public:    string largestNumber(vector<int> &num) {        vector<string> arr;        for(auto i:num)            arr.push_back(to_string(i));        sort(begin(arr), end(arr), [](string &s1, string &s2){ return s1+s2>s2+s1; });        string res;        for(auto s:arr)            res+=s;        while(res[0]=='0' && res.length()>1)            res.erase(0,1);        return  res;    }};