根据身高重建队列 脑筋急转弯
1. 题目描述
假设有打乱顺序的一群人站成一个队列,数组people表示队列中一些人的属性(不一定按顺序)。每个people[i] = [hi, ki]表示第i个人的身高为hi,前面 正好 有ki个身高大于或等于hi的人。
示例 1:
输入:people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
输出:[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
解释:
编号为 0 的人身高为 5 ,没有身高更高或者相同的人排在他前面。
编号为 1 的人身高为 7 ,没有身高更高或者相同的人排在他前面。
编号为 2 的人身高为 5 ,有 2 个身高更高或者相同的人排在他前面,即编号为 0 和 1 的人。
编号为 3 的人身高为 6 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。
编号为 4 的人身高为 4 ,有 4 个身高更高或者相同的人排在他前面,即编号为 0、1、2、3 的人。
编号为 5 的人身高为 7 ,有 1 个身高更高或者相同的人排在他前面,即编号为 1 的人。
因此 [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 是重新构造后的队列。
2. 题解
2.1 从低到高考虑。
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, new Comparator<int[]>() {
public int compare(int[] person1, int[] person2) {
if (person1[0] != person2[0]) {
return person1[0] - person2[0];
} else {
return person2[1] - person1[1];
}
}
});
int n = people.length;
int[][] ans = new int[n][];
for (int[] person : people) {
int spaces = person[1] + 1;
for (int i = 0; i < n; ++i) {
if (ans[i] == null) {
--spaces;
if (spaces == 0) {
ans[i] = person;
break;
}
}
}
}
return ans;
}

[5,0]有0个身高更高或者相同的人排在他前面。[7,0]不能排在[5,0]前面,而[4,0]可以排在[5,0]前面。这里由于没有[4,0]且还没有遍历到[7,0],所以遍历到[5,0]时可以把它放到位置0上。
[5,2]有2个身高更高或者相同的人排在他前面,注意到身高相同的[5,0]排在它前面。
如果先遍历[5,2],再遍历[5,0],每次遍历只需要考虑要在前面留多少个空位。
如果先遍历[5,0],再遍历[5,2],那么每次遍历先要判断前后两个人的身高是否相同,再考虑要在前面留多少个空位。
2.2 从高到低考虑。
public int[][] reconstructQueue(int[][] people) {
Arrays.sort(people, new Comparator<int[]>() {
public int compare(int[] person1, int[] person2) {
if (person1[0] != person2[0]) {
return person2[0] - person1[0];
} else {
return person1[1] - person2[1];
}
}
});
List<int[]> ans = new ArrayList<int[]>();
for (int[] person : people) {
ans.add(person[1], person);
}
return ans.toArray(new int[ans.size()][]);
}
这里借助ArrayList的add(int index, E element)方法,在指定位置插入指定元素,如果该位置上有元素,就将该位置上的元素及其后续的元素右移。

注意到[5,0]和[5,2]有相同的身高,且[5,0]只能排在[5,2]前面。如果先遍历[5,2],再遍历[5,0],那么[5,2]会在[7,0]和[6,1]后面,接着[5,0]又跑到[7,0]和[6,1]前面,这样会导致[5,2]有3个身高更高或者相同的人排在他前面,这显然是不对的,因此,这里要先遍历[5,0],再遍历[5,2]。

参考:

浙公网安备 33010602011771号