Java – no suitable method for sort (int [], >) found
Algorithm problem: given a list of nonnegative integers, arrange them into the largest number
For example, given [3,30,34,5,9], the maximum number of formations is 9534330
Note: the result can be very large, so you need to return a string instead of an integer
public class Solution { public String largestNumber(int[] num) { Arrays.sort(num,new java.util.Comparator<Integer>() { @Override public int compare(Integer a,Integer b) { String s1 = String.valueOf(a),s2 = String.valueOf(b); return Integer.parseInt(s1 + s2) - Integer.parseInt(s2 + s1); } }); StringBuilder builder = new StringBuilder(); for (int i = num.length - 1; i >= 0; i--) builder.append(num[i]); return builder.toString(); } }
Result: Line 3: error: no suitable method was found for sort (int [], < anonymous comparator < integer > >)
Who knows how to modify it? thank you!
Thank you for all your detailed answers. I have modified my code to
public String largestNumber(int[] num) { int N = num.length; String[] aux = new String[N]; for (int i = 0; i < N; i++) aux[i] = String.valueOf(num[i]); // int[] -> String[] Arrays.sort(aux,new Comparator<String>() { @Override public int compare(String a,String b) { return (int) (Long.parseLong(a + b) - Long.parseLong(b + a)); // note the overflow of int,max + max } }); StringBuilder builder = new StringBuilder(); for (int i = N - 1; i >= 0; i--) builder.append(aux[i]); int sub = 0; for ( ; sub < builder.length() - 1 && builder.charAt(sub) == '0'; sub++); return builder.substring(sub).toString(); }
I'm still trying to find ways to avoid using extra space
Solution
The reason is that int and integer are different types Int is a primitive and integer is its object wrapper Comparison < T > applies only to objects; It does not apply to primitives
Put the integer into the container of integers, for example, ArrayList < integer >, and use the comparator to solve the problem
Note that for very large integers, your method may fail because concatenating two valid integers may produce a number too large to hold int You can return to (S1, S2) CompareTo (S2 S1) instead of dictionary comparison, which is the same as that of numbers of the same length