11/16
杂记:
想直接用JAVA写
然后发现Arraylist不会用
特意去看了一下JAVA编程思想中List的相关章节
中文版p454 原版p781
知识点汇总:
二维数组的行数:a.length
二维数组的列数:a[0].length
排序
Arrays.sort(people, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[0]==o2[0]) return o1[1]-o2[1];
return o1[0]-o2[0];
}
});
题目
假设有打乱顺序的一群人站成一个队列。
每个人由一个整数对(h, k)表示,
其中h是这个人的身高,
k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。
注意:
总人数少于1100人。
JAVA代码
解法:
按身高从小到大排序,之前比他高的人从大到小排序。
身高小的人先排序,因为他要为在其前面为比他高或一样高的k个人留出座位。
而因为一样高的人也算在k里面,所以让k从大到小排序。(如果k也从小到大排序的话,那么在检索没有使用过的位置的时候,还要特判一下这个位置的h是不是和当前匹配的h相同,浪费时间)
class Solution {
public int[][] reconstructQueue(int[][] people) {
int[][] ans = new int[people.length][2];
Arrays.sort(people, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if (o1[0] == o2[0]) return o2[1] - o1[1];
return o1[0] - o2[0];
}
});
int judge[] = new int[people.length];
for (int i : judge) judge[i] = 0;
int cnt = 0;
for (int i = 0; i < people.length; i++) {
for (int j = 0; j < ans.length; j++) {
if (judge[j] == 1) continue;
if (cnt == people[i][1]) {
cnt = 0;
ans[j] = people[i];
judge[j] = 1;
break;
}
else cnt++;
}
}
return ans;
}
}