题目:
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.
链接:http://leetcode.com/problems/largest-number/
6/20/2017
最初的想法是改动MSD来排序,但是如果位数不一样需要补前一个高位的char,而不是'',很麻烦。
参考别人的sort方法,很好很强大。
注意:
1. Arrays.sort(), Comparator接口当中要实现compare函数
2. 当输入全是0时返回0
1 public class Solution { 2 public String largestNumber(int[] nums) { 3 if (nums == null || nums.length == 0) { 4 return ""; 5 } 6 String[] numsInString = new String[nums.length]; 7 8 for (int i = 0; i < nums.length; i++) { 9 numsInString[i] = Integer.toString(nums[i]); 10 } 11 Arrays.sort(numsInString, new Comparator<String>() { 12 public int compare(String s1, String s2) { 13 String s1s2 = s1 + s2; 14 String s2s1 = s2 + s1; 15 return s1s2.compareTo(s2s1); 16 } 17 }); 18 if (numsInString[numsInString.length - 1].equals("0")) { 19 return "0"; 20 } 21 StringBuilder sb = new StringBuilder(); 22 for (int i = numsInString.length - 1; i >= 0; i--) { 23 sb.append(numsInString[i]); 24 } 25 return sb.toString(); 26 } 27 }
也可以比较的时候直接返回reverse order
https://discuss.leetcode.com/topic/8018/my-java-solution-to-share
Java 8的简介写法
https://discuss.leetcode.com/topic/7235/my-3-lines-code-in-java-and-python
更多讨论