[英]Sort 2D Array to one column in ascending order
I made this code for sorting the 2D array.我编写了用于对二维数组进行排序的代码。 I have to check on "duplicates" and "one empty column", but don't know which method to use我必须检查“重复项”和“一个空列”,但不知道使用哪种方法
example:例子:
1 2 3
1 4
3 2
3 3 5
result:结果:
3 2
3 3 5
1 2 3
1 4
public int[][] arrSort(int[][] arr) {
Arrays.sort(arr, (obj1, obj2) -> {
if (obj1.length == 0) { return 1; }
if (obj2.length == 0) { return -1; }
int min = Math.min(obj1.length, obj2.length);
for (int i = 0; i < min ; i++) {
if (obj1[i] != obj2[i]) {
return obj2[i] - obj1[i];
}
}
return 1;
});
return arr;}}
I have managed to fix the code for you, and I also added some comments for you to use and understand.我已经设法为您修复了代码,并且还添加了一些注释供您使用和理解。
I fixed the answer with better code and more edge cases.我用更好的代码和更多的边缘情况修复了答案。
private static int[][] sort(int[][] arr) {
Arrays.sort(arr, (obj1, obj2) -> {
if(obj1.length == 0) return 1; // Make the first array go backwards if it has no items
if(obj2.length == 0) return -1; // Make the second array go backwards if it has no items
if(obj1.length > obj2.length) return -1;
if(obj2.length > obj1.length) return 1;
int score1 = 0, score2 = 0;
for (int i = 0; i < obj1.length; i++) {
if(obj1[i] > obj2[i])
score1++;
else if(obj2[i] > obj1[i])
score2++;
}
// Make the result negative
return -Integer.compare(score1, score2);
});
return arr;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.