179. Largest Number

来源:互联网 发布:apache thrift book 编辑:程序博客网 时间:2024/05/22 17:42

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.

例如:str1=12,str2=9,那么str1+str2=129, str2+str1=912,明显后者更大。以这个标准重写compare函数。代码如下:

public class Solution {    public String largestNumber(int[] nums) {        if (nums.length == 0) {            return "0";        }        String[] strs = new String[nums.length];        for (int i = 0; i < nums.length; i ++) {            strs[i] = nums[i] + "";        }        Arrays.sort(strs, new Comparator<String>() {            @Override            public int compare(String i, String j) {                String s1 = i + j;                String s2 = j + i;                return s1.compareTo(s2);            }        });        if (strs[strs.length - 1].charAt(0) == '0') {            return "0";        }        StringBuilder builder = new StringBuilder();        for (int i = strs.length - 1; i >= 0; i --) {            builder.append(strs[i]);        }        return builder.toString();    }}

原创粉丝点击