Problem: Given a list of non negative integers, arrange them such that they form the largest number.
My approach:
public class Solution implements Comparator<Integer>{
public String largestNumber(final List<Integer> A) {
List<Integer> B = A;
Collections.sort(B);
String ans = "";
for(int i=B.size()-1;i>=0;i--)
ans = ans+Integer.toString(B.get(i));
return ans;
}
public int compare(Integer a,Integer b){
String as = Integer.toString(a);
String bs = Integer.toString(b);
String fe = as+bs;
String se = bs+as;
return (fe.compareTo(se));
}
}
Problems arising: For A = [3, 30, 34, 5, 9] the output being shown is 3430953 but expected output is 9534330.
From what I can see array list is sorted normally without using custom made compare() method. Why is this happening?
Where you have this:
Collections.sort(B);
you are sorting with the natural order of the elements because you don't specify a comparator.
Since you are inside the Solution
class, and it implements Comparator<Integer>
, you probably mean:
Collections.sort(B, this);
so you will actually use the ordering that you have defined.
Python Version :
import functools
from functools import cmp_to_key
num=[3, 30, 34, 5, 9]
def compare(n1, n2):
if n1 + n2 > n2 + n1:
return 1
elif n1 + n2 < n2 + n1:
return -1
else:
return 0
num_str = [str(n) for n in num]
res = ""
print(num_str)
res=""
for n in sorted(num_str,key=functools.cmp_to_key(compare),reverse=True) :
res += n
print(res)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.