Skip to content

Latest commit

 

History

History
57 lines (44 loc) · 1.21 KB

179. Largest Number.md

File metadata and controls

57 lines (44 loc) · 1.21 KB

179. Largest Number

Given a list of non negative integers, arrange them such that they form the largest number.

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

代码

class Solution {
    public String largestNumber(int[] nums) {
        if (nums == null || nums.length == 0)
            return "";
        
        String[] snum = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            snum[i] = String.valueOf(nums[i]);
        }

        Comparator<String> comp = new Comparator<String>(){
            @Override
            public int compare(String o1, String o2) {
                // TODO Auto-generated method stub
                String s1 = o1 + o2;
                String s2 = o2 + o1;
                return s2.compareTo(s1);
            }
        };

        Arrays.sort(snum, comp);
        // if all digits are zero
        if (snum[0].charAt(0) == '0')
            return "0";
        
        StringBuilder sb = new StringBuilder();
        for (String s: snum) {
            sb.append(s);
        }
        return sb.toString();
    }
}