lintcode-最大数-184

给出一组非负整数,重新排列他们的顺序把他们组成一个最大的整数


样例


给出样例 [1, 20, 23, 4, 8],返回组合最大的整数为8423201


注意 最后的结果可能很大,所以我们返回一个字符串来代替这个整数


C++耗时:25ms

string itoa(int a){
        if(a==0)
            return "0";
        string ret;
        while(a){
            ret+=a%10+'0';
            a/=10;
        }
        reverse(ret.begin(),ret.end());
        return ret;
}

bool cmp(int a,int b){
    string sa;
    string sb;
    
    sa=itoa(a);
    sb=itoa(b);
    return sb+sa>sa+sb?false:true;    
     
}
class Solution {
public:
    
    string largestNumber(vector<int> &num) {
        if(num.size()==1)
            return itoa(num[0]);
        bool flg=true;
        for(auto e:num){
            if(e!=0)
                flg=false;
        }    
        if(flg)
            return "0";
        sort(num.begin(),num.end(),cmp);

        string ret;
        
        for(auto e:num){
            
            ret+=itoa(e);
        }
        return ret;    
    }
};
Java 耗时: 1848ms

class NumbersComparator implements Comparator<String> {
	@Override
	public int compare(String s1, String s2) {
		return (s2 + s1).compareTo(s1 + s2);
	}
}

public class Solution {
    
    public String largestNumber(int[] nums) {
        String[] strs = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            strs[i] = Integer.toString(nums[i]);    // int to string
        }
        Arrays.sort(strs, new NumbersComparator());
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strs.length; i++) {
            sb.append(strs[i]);
        }
        String result = sb.toString();
        
        int index = 0;
        while (index < result.length() && result.charAt(index) == '0') {
            index++;
        }
        if (index == result.length()) {
            return "0";
        }
        return result.substring(index);     // substring(int beginIndex)
    }
}


你可能感兴趣的:(lintcode-最大数-184)