Monday, October 26, 2015

[leetcode]Largest Number

这题没想到怎么对比 前续相同的string的前后....
后来发现可以直接 对比 究竟是s1+s2大 还是s2+s1大....就可以了
还有一个case是当 array里面全是0, 长度大于等于2的时候

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
    public String largestNumber(int[] nums) {
        String[] result = new String[nums.length];
        for (int i = 0; i < nums.length; i++){
            result[i] = ""+nums[i];
        }
        Arrays.sort(result, new Comparator<String>(){
            public int compare(String s1, String s2){
                String o1 = s1+s2;
                String o2 = s2+s1;
                return o2.compareTo(o1);
            }
        });
        String output = "";
        for (int i = 0; i <result.length; i++){
            output += result[i];
        }
        if (output.charAt(0)=='0'){
            return "0";
        }
        return output;
    }
}

No comments:

Post a Comment