406-根据身高重建队列

406-根据身高重建队列

力扣406

https://leetcode-cn.com/problems/queue-reconstruction-by-height/

思路很重要

先排序:身高从低到高排序,前面人数从大到小排序

排完后[[4,4],[5,2],[5,0],[6,1],[7,1],[7,0]]

从后往前遍历

[7,1]表示往后挪一个:[[4,4],[5,2],[5,0],[6,1],[7,0],[7,1]]

[6,1]表示往后挪一个:[[4,4],[5,2],[5,0],[7,0],[6,1],[7,1]]

后同…

代码不难,思维题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int[][] reconstructQueue(int[][] people) {
//身高从低到高排序,前面人数从大到小排序
Arrays.sort(people, (o1, o2) -> {
if (o1[0] != o2[0]) return o1[0] - o2[0];
else return o2[1] - o1[1];
});
//从后往前调整顺序,people[i, j]表示people[i]往后调整j个
for (int i = people.length - 2; i >= 0; i--) {
int time = people[i][1];
int[] temp = people[i];
for (int j = i; j < i + time; j++) {
people[j] = people[j + 1];
}
people[i + time] = temp;
}
return people;
}

其他题目点击这里

#
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×