O(n^2) Java Solution, using string to compare


  • 1
    J
    public String largestNumber(int[] nums) {
    	String[] numbers = new String[nums.length];
    	for(int i = 0; i < nums.length; i++) {
    		numbers[i] = String.valueOf(nums[i]);
    	}
        Arrays.sort(numbers, new Comparator<String>() {
    		public int compare(String o1, String o2) {
    			String s1 = o2 + o1;
    			String s2 = o1 + o2;
    			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;
    		}
    	});
        StringBuilder sb = new StringBuilder();
        for(String s : numbers)
        	sb.append(s);
        String res = sb.toString();
        return res.charAt(0) == '0' ? "0" : res;
    }

Log in to reply
 

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