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.
SOLUTION 1:
参考http://bookshadow.com/weblog/2015/01/13/leetcode-largest-number/的解法:
贪心思路:对于两个备选数字a和b,如果str(a) + str(b) > str(b) + str(a),则a在b之前,否则b在a之前
按照此原则对原数组从大到小排序即可
时间复杂度O(nlogn)
易错样例:
Input: [0,0]
Output: "00"
Expected: "0"
JAVA CODE:
1 public class Solution { 2 public String largestNumber(int[] num) { 3 // 1045 4 // 1111 begin. 5 if (num == null) { 6 return null; 7 } 8 9 ArrayList<Integer> list = new ArrayList<Integer>(); 10 for (int n1: num) { 11 list.add(n1); 12 } 13 14 Collections.sort(list, new Comparator<Integer>(){ 15 public int compare(Integer o1, Integer o2) { 16 String s1 = "" + o1 + o2; 17 String s2 = "" + o2 + o1; 18 19 return s2.compareTo(s1); 20 } 21 }); 22 23 StringBuilder sb = new StringBuilder(); 24 for (int n: list) { 25 sb.append(n); 26 } 27 28 if (sb.charAt(0) == '0') { 29 return "0"; 30 } 31 32 return sb.toString(); 33 } 34 }