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.
Have you met this question in a real interview?
思路: 第一想法是类似于premutation II 的解法, 用dfs可以解决, 但肯定 超时。
于是想到了利用 heap 来做, 关键点在于comparator, 直接比较会因为有长度不同的原因导致有错误case
后来想了好久, 利用 s1 + s2 和 s2 + s1 来进行比较,可以完美的解决这个问题, 因为他的本质比较就是相加后比较。
public class Solution {
public String largestNumber(int[] num) {
if (num.length < 0)
return "";
Comparator<String> comparator = new Comparator<String>() {
public int compare(String s1, String s2) {
String l1 = s1 + s2;
String l2 = s2 + s1;
for (int i = 0; i < l1.length(); i++) {
if (l1.charAt(i) > l2.charAt(i))
return -1;
else if (l1.charAt(i) < l2.charAt(i))
return 1;
}
return 0;
}
};
Queue<String> queue = new PriorityQueue<String>(num.length, comparator);
for (int i : num)
queue.add(String.valueOf(i));
StringBuilder sb = new StringBuilder();
while (!queue.isEmpty())
sb.append(queue.poll());
if(sb.charAt(0) == '0'){//All 0s situation
sb = (new StringBuilder()).append('0');
}
return sb.toString();
}
}
超时解法:
public String largestNumber(int[] num) {
if (num.length < 0)
return "";
Arrays.sort(num);
String[] ret = { "0" };
permutation(num, 0, ret);
return ret[0];
}
private void permutation(int[] num, int start, String[] ret) {
if (start >= num.length) {
StringBuilder sb = new StringBuilder();
for (int i : num)
sb.append(i);
String s = sb.toString();
if (ret[0].compareTo(s) < 0) {
ret[0] = s;
}
return;
}
HashSet<Integer> visited = new HashSet<Integer>();
for (int i = start; i < num.length; i++) {
if (!visited.contains(num[i])) {
swap(num, i, start);
permutation(num, start + 1, ret);
swap(num, i, start);
visited.add(num[i]);
}
}
}