2336. 无限集中的最小数字

2336. 无限集中的最小数字

解法一: 有序哈希

java
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
class SmallestInfiniteSet {

private TreeSet<Integer> treeSet;

public SmallestInfiniteSet() {
treeSet = new TreeSet<>();
for (int i = 1; i <= 1000; i++) {
treeSet.add(i);
}
}

public int popSmallest() {
return treeSet.pollFirst();
}

public void addBack(int num) {
treeSet.add(num);
}

}

/**
* Your SmallestInfiniteSet object will be instantiated and called as such:
* SmallestInfiniteSet obj = new SmallestInfiniteSet();
* int param_1 = obj.popSmallest();
* obj.addBack(num);
*/

解法二: 优先级队列

java
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
class SmallestInfiniteSet {

private PriorityQueue<Integer> priorityQueue;

private boolean[] exists;

private int min;

public SmallestInfiniteSet() {
priorityQueue = new PriorityQueue<>((num1, num2) -> num1 - num2);
min = 1;
exists = new boolean[1001];
}

public int popSmallest() {
if (!priorityQueue.isEmpty() && exists[priorityQueue.peek()]) {
Integer ans = priorityQueue.poll();
exists[ans] = false;
return ans;
}
return min++;
}

public void addBack(int num) {
if (num < min && !exists[num]) {
priorityQueue.offer(num);
exists[num] = true;
}
}

}

/**
* Your SmallestInfiniteSet object will be instantiated and called as such:
* SmallestInfiniteSet obj = new SmallestInfiniteSet();
* int param_1 = obj.popSmallest();
* obj.addBack(num);
*/
作者

wuhunyu

发布于

2023-11-29

更新于

2023-11-29

许可协议