[英]Sort 2D Array to one column in ascending order
我編寫了用於對二維數組進行排序的代碼。 我必須檢查“重復項”和“一個空列”,但不知道使用哪種方法
例子:
1 2 3
1 4
3 2
3 3 5
結果:
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;}}
我已經設法為您修復了代碼,並且還添加了一些注釋供您使用和理解。
我用更好的代碼和更多的邊緣情況修復了答案。
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.