Solution in Java


  • 0
    B
    public String largestNumber(int[] input) {
        if(input == null || input.length == 0) return "";
        if(input.length == 1) return String.valueOf(input[0]);
        String[] strs = new String[input.length];
        for(int i = 0; i < input.length; i++) {
            strs[i] = String.valueOf(input[i]);
        }
        Comparator<String> c = new Comparator<String>() {
            public int compare(String s1, String s2) {
                int len1 = s1.length();
                int len2 = s2.length();
                int i = 0;
                while(i < 2 * len1 || i < 2 * len2) {
                    int index1 = i % len1;
                    int index2 = i % len2;
                    if(s1.charAt(index1) > s2.charAt(index2)) return -1;
                    else if(s1.charAt(index1) < s2.charAt(index2)) return 1;
                    i++;
                }
                return 0;
            }
        };
        Arrays.sort(strs, c);
        if(Integer.valueOf(strs[0]) == 0) return "0";
        StringBuilder ret = new StringBuilder();
        for(String str : strs) ret.append(str);
        return ret.toString();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.