-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy path_406_reconstructQueue.java
More file actions
70 lines (63 loc) · 2.26 KB
/
_406_reconstructQueue.java
File metadata and controls
70 lines (63 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package pp.arithmetic.leetcode;
import pp.arithmetic.Util;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* Created by wangpeng on 2019-08-27.
* 406. 根据身高重建队列
* <p>
* 假设有打乱顺序的一群人站成一个队列。 每个人由一个整数对(h, k)表示,其中h是这个人的身高,k是排在这个人前面且身高大于或等于h的人数。 编写一个算法来重建这个队列。
* <p>
* 注意:
* 总人数少于1100人。
* <p>
* 示例
* <p>
* 输入:
* [[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]
* <p>
* 输出:
* [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/queue-reconstruction-by-height
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class _406_reconstructQueue {
public static void main(String[] args) {
_406_reconstructQueue reconstructQueue = new _406_reconstructQueue();
int[][] ints = reconstructQueue.reconstructQueue(new int[][]{
{7, 0}, {7, 1}, {6, 1}, {5, 0}, {5, 2}, {4, 4}
});
for (int i = 0; i < ints.length; i++) {
Util.printArray(ints[i]);
}
}
/**
* 解题思路:先排序再插入
* 1.排序规则:按照先H高度降序,K个数升序排序
* 2.遍历排序后的数组,根据K插入到K的位置上
*
* 核心思想:高个子先站好位,矮个子插入到K位置上,前面肯定有K个高个子,矮个子再插到前面也满足K的要求
*
* @param people
* @return
*/
public int[][] reconstructQueue(int[][] people) {
// [7,0], [7,1], [6,1], [5,0], [5,2], [4,4]
// 再一个一个插入。
// [7,0]
// [7,0], [7,1]
// [7,0], [6,1], [7,1]
// [5,0], [7,0], [6,1], [7,1]
// [5,0], [7,0], [5,2], [6,1], [7,1]
// [5,0], [7,0], [5,2], [6,1], [4,4], [7,1]
Arrays.sort(people, (o1, o2) -> o1[0] == o2[0] ? o1[1] - o2[1] : o2[0] - o1[0]);
LinkedList<int[]> list = new LinkedList<>();
for (int[] i : people) {
list.add(i[1], i);
}
return list.toArray(new int[list.size()][2]);
}
}