给定一个由非负整数组成的数组,求将数组中元素拼接后,形成的最大数

2017-04-04  本文已影响247人  敲一手烂代码
public String largestNumber(int[] nums) {
        if (nums == null || nums.length == 0) {
            return "";
        }
        String numStrList[] = new String[nums.length]; 
        for (int i = 0; i < numStrList.length; i++) {
            numStrList[i] = String.valueOf(nums[i]);
        }
        Comparator<String> comparator = new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                String str1 = s1 + s2;
                String str2 = s2 + s1; 
                return str2.compareTo(str1);
            }
        };
        Arrays.sort(numStrList, comparator);
        String s = "";
        for (String string : numStrList) {
            s += string;
        }
        if (s.charAt(0) == '0') {
            return "0";
        }
        return s;
    }
上一篇下一篇

猜你喜欢

热点阅读