数组排序的Java比较器 [英] java comparator for arrays sort
问题描述
我的代码如下所示:
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
第14行:错误:找不到合适的sort(int [],int,int,$ b方法$ b匿名比较器)
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!
推荐答案
没有像<$ c $这样的方法接受 primitive 数组c> int []数字并按降序对其进行排序。有些对象采用一系列对象,例如 sort(T [] a,Comparator <?super T> c)
-但原语不是对象
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 Objects
1.
最直接的方法可能就是按升序对数组进行排序(int []输入)
,然后反转结果数组。排序可能要比反向排序花费更长的时间,因此此方法应能表现良好。或者,您可以修改使用代码,以使其按升序处理数组,或者可以将数组包装在 List
中,然后使用反向视图
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.
有还有很多其他选择。
1 原则上,通过将每个基础装箱,将您的
元素,但是这样做会付出巨大的性能损失和巨大的内存(将使用的内存增加大约10倍)和垃圾罚款。 int []
转换为 Integer []
int
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.
这篇关于数组排序的Java比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!