-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSmallestInfiniteSet.java
More file actions
49 lines (40 loc) · 1.42 KB
/
Copy pathSmallestInfiniteSet.java
File metadata and controls
49 lines (40 loc) · 1.42 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
package LeetcodePractice;
import java.util.PriorityQueue;
import java.util.HashSet;
import java.util.*;
class SmallestInfiniteSet {
private int current;
private PriorityQueue<Integer> addedBack;
private HashSet<Integer> inHeap;
public SmallestInfiniteSet() {
current = 1;
addedBack = new PriorityQueue<>();
inHeap = new HashSet<>();
}
public int popSmallest() {
if (!addedBack.isEmpty()) {
int smallest = addedBack.poll();
inHeap.remove(smallest);
return smallest;
} else {
return current++;
}
}
public void addBack(int num) {
if (num < current && !inHeap.contains(num)) {
addedBack.offer(num);
inHeap.add(num);
}
}
public static void main(String[] args) {
SmallestInfiniteSet smallestInfiniteSet = new SmallestInfiniteSet();
smallestInfiniteSet.addBack(2);
System.out.println(smallestInfiniteSet.popSmallest());
System.out.println(smallestInfiniteSet.popSmallest());
System.out.println(smallestInfiniteSet.popSmallest());
smallestInfiniteSet.addBack(1);
System.out.println(smallestInfiniteSet.popSmallest());
System.out.println(smallestInfiniteSet.popSmallest());
System.out.println(smallestInfiniteSet.popSmallest());
}
}