[Leetcode] 179. Largest Number

  1. Largest Number
    Given a list of non negative integers, arrange them such that they form the largest number.
    For example, given [3, 30, 34, 5, 9]
    , the largest formed number is 9534330
    .
    Note: The result may be very large, so you need to return a string instead of an integer.
    Credits:Special thanks to @ts for adding this problem and creating all test cases.

JAVA:

public class Solution {
    class strComparator implements Comparator{
        public final int compare(Object pFirst, Object pSecond){
            String first = (String)pFirst, second = (String)pSecond;
            String a = first + second;
            String b = second + first;
            return -(a.compareTo(b));
        }
    }
    public String largestNumber(int[] nums) {
        int len = nums.length;
        String[] str = new String[len];
        for(int i = 0; i < len; i++){
            str[i] = Integer.toString(nums[i]);
        }
        Arrays.sort(str, new strComparator());
        String ret = "";
        for(int i = 0; i < str.length; i++) ret += str[i];
        int idx = 0;
        for(; idx < ret.length(); idx++){
            if(ret.charAt(idx) != '0' || idx == ret.length()-1) break;
        }
        ret = ret.substring(idx,ret.length());
        if(str.length == 0) ret = "0";
        return ret;
    }
}

你可能感兴趣的:([Leetcode] 179. Largest Number)