身高從低到高,身高相同體重從輕到重,體重相同維持原來順序。
輸入
4
100 100 120 130
40 30 60 50
輸出:
2 1 3 4
輸入
3
90 110 90
45 60 45
輸出
1 3 2
查看代碼
import java.util.*;
public class Demo17 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String[] high = sc.nextLine().split(" ");
String[] weigh = sc.nextLine().split(" ");
//身高、體重、序號三個變量的處理
int[][] ints = new int[n][3];
for(int i = 0; i < n; i++){ //好好理解二維數組,從一維到二維,行列角度
ints[i][0] = i + 1;
ints[i][1] = Integer.parseInt(high[i]);
ints[i][2] = Integer.parseInt(weigh[i]);
}
Arrays.sort(ints, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[1] == o2[1])
return o1[2] -o2[2];
else
return o1[1] - o2[1];
}
});
for(int[] i : ints){
System.out.print(i[0] + " ");
}
}
}
思考:為什么在定義二維數組時,不是 int[][] ints = new int[3][n]?
在排序時,(int[] o1, int[] o2) 其中的o1 o2存儲的數據有哪些?
本質上還是一維,只不過相對於普通一維中存儲的是基本類型,這里存儲的數組類型,==》形成二維。