码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode:Largest Number

时间:2015-02-17 14:08:08      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:largest number   sort   erase   

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都是迭代器)

java实现版本:

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;

}
}


Leetcode:Largest Number

标签:largest number   sort   erase   

原文地址:http://blog.csdn.net/wolongdede/article/details/43865993

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!