Easy to understand Java solution


  • 0
    G

    Intuition:

    Given two integers, A and B, we simply try both concatenation AB and BA and determine which one goes first.
    E.g. Let A = 3, B = 34; AB = 334, BA = 343; Since BA > AB, we know B goes before A

    We sort the int array using the above method in descending order and output the string representation of the ordered list.

    class Solution {
        public String largestNumber(int[] nums) {
            String ans = "";
            if(nums.length == 0) return ans;
            List<Integer> list = new ArrayList<Integer>(); 
            for(int n : nums)
                list.add(n);
            Collections.sort(list, new sortNum());
            
            for(int n : list){
                ans += String.valueOf(n);
            }
            if(ans.charAt(0) == '0') return "0";
            return ans;        
        }
        class sortNum implements Comparator<Integer>{
            @Override
            public int compare(Integer a, Integer b) {
                String strA = String.valueOf(a);
                String strB = String.valueOf(b);
                String ab = strA + strB;
                String ba = strB + strA;
                return (int) (Long.parseLong(ba) - Long.parseLong(ab));
            }
        }
    }
    

    Note that if our ordered list are 0s, we should output "0" instead of a string of zeros.


Log in to reply
 

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