您的位置:首页 > 其它

Leetcode Largest Number

2016-07-19 04:43 295 查看
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.

Difficulty: Medium

public class Solution {
public String largestNumber(int[] nums) {
String[] list = new String[nums.length];
for(int i = 0; i < nums.length; i++){
list[i] = Integer.toString(nums[i]);
}
Arrays.sort(list, new Comparator<String>(){
public int compare(String s1, String s2){
String leftRight = s1+s2;
String rightLeft = s2+s1;
return -leftRight.compareTo(rightLeft);
}
});
String ans = "";
for(String str : list){
ans = ans + str;
}
if(ans.length() == 0 || ans.charAt(0) == '0')
return "0";
return ans;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: