-
Notifications
You must be signed in to change notification settings - Fork 0
/
MostRecentKUrls.java
89 lines (82 loc) · 2.1 KB
/
MostRecentKUrls.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
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.net.URL;
import java.util.Map;
public class MostRecentKUrls {
static class URLNode {
String url;
URLNode prev;
URLNode next;
URLNode(String url) {
this.url = url;
}
}
URLNode head;
URLNode tail;
int capacity;
Map<String, URLNode> URLNodeMap;
int size;
MostRecentKUrls(int capacity) {
if (capacity == 0) {
throw new IllegalArgumentException("capacity cannot be 0");
}
this.capacity = capacity;
URLNodeMap = new HashMap<>();
size = 0;
}
public void update(String url) {
if (url == null) {
throw new IllegalArgumentException("url cannot be null");
}
URLNode node = null;
if (URLNodeMap.containsKey(url)) {
node = URLNodeMap.get(url);
remove(node);
size--;
} else if (size == capacity) {
node = tail;
remove(node);
size--;
node.url = url;
} else {
node = new URLNode(url);
}
append(node);
size++;
}
public List<String> getMostRecentK() {
List<String> topKRecentUrls = new ArrayList<>();
URLNode curNode = head;
while (curNode != null) {
topKRecentUrls.add(curNode.url);
curNode = curNode.next;
}
return topKRecentUrls;
}
private void append(UrlNode node) {
URLNodeMap.put(node.url, node);
if (head == null) {
head = node;
tail = node;
} else {
node.next = head;
head.prev = node;
head = node;
}
}
private void remove(Node node) {
URLNodeMap.remove(node.url);
if (node.prev != null) {
node.prev.next = node.next;
}
if (node.next != null) {
node.next.prev = node.prev;
}
if (node == head) {
head = head.next;
}
if (node == tail) {
tail = tail.prev;
}
node.next = null;
node.prev = null;
}
}