标签:
Problem:
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.
Analysis:
The problem is also a new kind of problem!!! The solution is a magic!!! Wrong direction: try to use the digit to arrange those numbers. This method is very problemetic, since not all nums in the same length!!! Compare which digit??? A more smart way is to take advantage the sorting in the language, rather than to design our own version. Key: since those nums were designed to concatenate with each other, rather than add. Besides the way to multiply a number: num1 * 100 + num2 Why not we directly use String concatenation: str1 + str2. To make things better, since all the nums only include digits, we can directly compare the string representation of two numbers: nums1 < nums2 <====> nums1.toString < num2.toString How to arrange the concatenate order to make the result string be the largest? Define a comparator to sort strings, make the decision based on the concatnated string rather than s1 or s2. Arrays.sort(strs, new Comparator<String> () { public int compare(String s1, String s2) { String temp1 = s1 + s2; String temp2 = s2 + s1; return -1 * temp1.compareTo(temp2); } }); After the sort, we rank the first nums as the num would bigger than any other concatnnation. Also, the result the string may start with 0. Case: [0, 0, 0, 0] We should only keep one 0 if the answer is 0. while (buffer.length() > 1 && buffer.charAt(0) == ‘0‘) buffer.deleteCharAt(0); return buffer.toString(); Key: This problem is not logic hard, but requires some different ideas in comparison and sorting.
Solution:
public class Solution { public String largestNumber(int[] nums) { if (nums == null || nums.length == 0) return ""; String[] strs = new String[nums.length]; for (int i = 0; i < nums.length; i++) strs[i] = String.valueOf(nums[i]); Arrays.sort(strs, new Comparator<String> () { public int compare(String s1, String s2) { String temp1 = s1 + s2; String temp2 = s2 + s1; return -1 * temp1.compareTo(temp2); } }); StringBuffer buffer = new StringBuffer(); for (int i = 0; i < strs.length; i++) { buffer.append(strs[i]); } while (buffer.length() > 1 && buffer.charAt(0) == ‘0‘) buffer.deleteCharAt(0); return buffer.toString(); } }
标签:
原文地址:http://www.cnblogs.com/airwindow/p/4760003.html