Simple Java solution using Arrays.sort() and custom object implementing comparable


  • 11
    C
    public class Solution {
        public String largestNumber(int[] nums) {
            if(nums.length==0)return "";
            if(nums.length==1)return Integer.toString(nums[0]);
            NumStr[] n = new NumStr[nums.length];
            for(int i=0; i<nums.length; i++){
                n[i]=new NumStr(nums[i]);
            }
            Arrays.sort(n);
            if(n[0].num.equals("0"))return "0";
            StringBuilder b = new StringBuilder();
            for(int i=0; i<n.length; i++){
                b.append(n[i].num);
            }
            return b.toString();
        }
    }
    
    class NumStr implements Comparable<NumStr>{
        String num;
        public NumStr(int n){
            this.num=Integer.toString(n);
        }
        @Override
        public int compareTo(NumStr n){
            String s1=n.num+this.num;
            String s2=this.num+n.num;
            for(int i=0; i<s1.length(); i++){
                if(s1.charAt(i)>s2.charAt(i))return 1;
                else if(s1.charAt(i)<s2.charAt(i))return -1;
            }
            return 0;
        }
    }

  • 1
    C

    Great solution! Below is my solution using Comparator. The biggest difference is I use Integer as generic type in Comparator rather than customized object. Thereby we need to make a copy of nums at the beginning of main function.

    public class Solution {
        public String largestNumber(int[] nums) {
            String result = "";
            if (nums == null || nums.length == 0) return result; // special case
            Integer[] copy = new Integer[nums.length];
            for (int i = 0; i < nums.length; i++) copy[i] = nums[i];
            Arrays.sort(copy, new NumComparator()); // sort
            if (copy[copy.length - 1] == 0) return "0"; // if all element is 0, return "0"
            for (int i = copy.length - 1; i >= 0; i--) result += String.valueOf(copy[i]);
            return result;
        }
    }
    
    class NumComparator implements Comparator<Integer> {
        @Override
        public int compare(Integer i1, Integer i2) {
            String s1 = String.valueOf(i1) + String.valueOf(i2);
            String s2 = String.valueOf(i2) + String.valueOf(i1);
            for (int i = 0; i < s1.length(); i++) {
                if (s1.charAt(i) > s2.charAt(i)) return 1;
                if (s1.charAt(i) < s2.charAt(i)) return -1;
            }
            return 0;
        }
    }

Log in to reply
 

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