Java for LeetCode 179 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.

解题思路:

先把int数组转为String,然后做一个比较器,这里有一个小技巧可以用 (o2 + o1).compareTo(o1 + o2)作为比较器,可以将"大数字"放到前面,然后按照比较器的顺序输出即可,JAVA实现如下:

    public String largestNumber(int[] nums) {
String[] str=new String[nums.length];
for(int i=0;i<nums.length;i++)
str[i]=String.valueOf(nums[i]);
Comparator<String> comp = new Comparator<String>() {
public int compare(String o1, String o2) {
return (o2 + o1).compareTo(o1 + o2);
}
};
Arrays.sort(str, comp);
if (str[0].equals("0"))
return "0";
StringBuilder sb=new StringBuilder();
for (String s : str)
sb.append(s);
return sb.toString();
}
上一篇:说说SQL Server的数据类型


下一篇:C#连接SQL Server数据库进行简单操作