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.
思路:自己定义比较方法,对数组进行排序,然后把整数转化为字符串,依次连接起来即可。自定义排序比较方法:对于字符串S1,S2,比较连接起来(s1+s2与s2+s1)哪个更大。
实现代码:
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; } };附:
erase函数的原型如下:
(1)string& erase ( size_t pos = 0, size_t n = npos );
(2)iterator erase ( iterator position );
(3)iterator erase ( iterator first, iterator last );
也就是说有三种用法:
(1)erase(pos,n); 删除从pos开始的n个字符,比如erase(0,1)就是删除第一个字符
(2)erase(position);删除position处的一个字符(position是个string类型的迭代器)
(3)erase(first,last);删除从first到last之间的字符(first和last都是迭代器)
public class Solution { public String largestNumber(int[] num) { int len = num.length; String[] cache = new String[len]; String res = ""; for (int i = 0; i < len; i++) cache[i] = String.valueOf(num[i]); Arrays.sort(cache, new Comparator<String>() { @Override public int compare(String s1, String s2) { return (s1 + s2).compareTo(s2 + s1); } }); if (cache[len - 1].equals("0")) return "0"; for (int i = len - 1; i >= 0; i--) res += cache[i]; return res; } }
原文地址:http://blog.csdn.net/wolongdede/article/details/43865993