java comparator for arrays sort [duplicate]

时光怂恿深爱的人放手 提交于 2020-05-13 15:28:27

问题


My code is shown below:

public class Solution {
    public void nextPermutation(int[] nums) {
        int k = 0;
        for(int i = nums.length -1; i> 0 ;i--){
            if(nums[i-1] < nums[i]){
                k = i-1;
                break;
            }
        }
        if( k == 0) {Arrays.sort(nums); return;}
        int tmp = nums[k];
        nums[k] = nums[nums.length - 1];
        nums[nums.length-1] = tmp;
        Arrays.sort(nums,k+1,nums.length,new Comparator<Integer>(){
            public int compare(Integer a, Integer b){
                return b - a;
            }
        });
    }    
}

I want to sort the array in decreasing order by using comparator, but it always shows

Line 14: error: no suitable method found for sort(int[],int,int, anonymous Comparator)

Can anyone point out where is the problem? Thanks a lot!


回答1:


There is no method that takes a primitive array like int[] nums and sorts it in descending order. There are some that take an array of Objects, like sort(T[] a, Comparator<? super T> c) - but primitives are not Objects1.

The most straightforward method is likely to simply sort(int[] input) your array in ascending order, then reverse the resulting array. The sort is likely to take significantly longer than the reverse, so this method should perform well. Alternately, you may be able to modify the consuming code so that it deals with the array in ascending order, or you could wrap the array in a List and then use a reversed view.

There are lots of other options as well.


1 You could, in principle, convert your int[] into an Integer[], by boxing each underlying int element, but you would pay a large performance penalty and a huge memory (increasing the memory used by about 10x) and garbage penalty to do so.




回答2:


Your array is of type int and Comparator generic type is Integer. Change your array type to Integer and everything will be fine, like this:

public void nextPermutation(Integer[] nums) {...




回答3:


Your nums array must be of type Integer.




回答4:


The Arrays.sort overload that takes a Comparator can only work on arrays of Objects; int isn't a valid substitution for a generic type argument.

So,

Integer[] intObjs = ...;
int[] intPrimitives = ...;
Arrays.sort(intObjs, start, end, someComparator); //OK
Arrays.sort(intPrimitives, start, end, someComparator); //fails

For what you want to work, there'd have to be an Arrays.sort overload declared to take an int[] - but that'd be a costly sort, since it'd basically require boxing the ints for each comparison.



来源:https://stackoverflow.com/questions/39884385/java-comparator-for-arrays-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!