leetcode [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"

题目大意:

返回非负数数组数字组成的最大数字

解法:

利用java中自带的排序方法,并重写compare

java:

class Solution {
    public String largestNumber(int[] nums) {
        List<Integer> numbers=new ArrayList<Integer>();
        for(int i=0;i<nums.length;i++) numbers.add(nums[i]);
        Collections.sort(numbers, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return (o2.toString()+o1.toString()).compareTo(o1.toString()+o2.toString());
            }
        });
        StringBuilder res=new StringBuilder();
        for(int i=0;i<nums.length;i++){
            if(numbers.get(i)==0&&res.length()==0) continue;
            res.append(numbers.get(i).toString());
        }
        return res.length()==0?"0":res.toString();
    }
}

  

上一篇:Lambda表达式


下一篇:……