Java Solution, easy understand


  • 0
    A
    public class Solution {
        public String largestNumber(int[] nums){
            StringBuffer sb = new StringBuffer();
            Integer[] a = new Integer[nums.length];
            for(int i = 0; i < nums.length; i++){
                a[i] = nums[i];
            }
            Comparator l = new lComparator();
            Arrays.sort(a, l);
            for(int i = 0; i < a.length; i++){
                sb.append(a[i]);
            }
            if(sb.charAt(0) == '0'){
                return "0";
            }
            return new String(sb);
        }
    }
    
     class lComparator implements Comparator<Integer>{
        @Override
        public int compare(Integer n, Integer n2){
            //change n and n2 to int array
            int[]d1 = Integer.toString(n).chars().map(c -> c-='0').toArray();
            int[]d2 = Integer.toString(n2).chars().map(c -> c-='0').toArray();
            int i = 0;
            int j = 0;
            int loop1 = 0;
            int loop2 = 0;
            while(loop1 < 2 || loop2 < 2){
                if(d1[i] > d2[j]){
                    return -1;
                }else if(d1[i] < d2[j]){
                    return 1;
                }
                if(i != d1.length - 1){
                    i++;
                }else{
                    i = 0;
                    loop1++;
                }
                if(j != d2.length - 1){
                    j++;
                }else{
                    j = 0;
                    loop2++;
                }
            }
            return 0;
        }
    }

  • 0
    T

    what is loop1 and loop2 is for?


  • 0
    A

    To make sure every element of every int[] would be checked more than one time. example: 54 and 5454546


  • 0
    X

    Here is my comparator, might not be as efficient, but easy enough to understand:

    	public int compare(Integer arg0, Integer arg1) {
    		String s1 = arg0.toString();
    		String s2 = arg1.toString()+arg1.toString();
    
    		while (s1.length() < s2.length()) {
    			s1 += s1;
    		}
    		while (s2.length() < s1.length()) {
    			s2 += s2;
    		}
    		return s1.compareTo(s2);
    	}

Log in to reply
 

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