Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
98 lines (85 loc) · 2.58 KB

File metadata and controls

98 lines (85 loc) · 2.58 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
90
91
92
93
94
95
96
97
98
package LeetCode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class LeetCode146 {
private class Node {
Node next, prev;
int key, value;
Node (){}
Node(int key, int value) {
this.value = value;
this.key = key;
}
}
private Node head, tail;
private Map<Integer, Node> map = new HashMap<>();
private int count, capacity;
private void addNode(Node node) {
Node old = head.next;
head.next = node;
node.prev = head;
node.next = old;
old.prev = node;
}
private void removeNode(Node node) {
Node previous = node.prev;
previous.next = node.next;
node.next.prev = previous;
}
private void moveToHead(Node node) {
removeNode(node);
addNode(node);
}
private Node popTail() {
Node pre = tail.prev;
removeNode(pre);
return pre;
}
public LeetCode146(int capacity) {
this.capacity = capacity;
this.count = 0;
head = new Node();
tail = new Node();
head.next = tail;
tail.prev = head;
}
public int get(int key) {
Node node = map.get(key);
if (node == null) return -1;
moveToHead(node);
return node.value;
}
public void put(int key, int value) {
Node node = map.get(key);
if (node == null) {
if (count == capacity) {
map.remove(popTail().key);
--count;
}
Node fresh = new Node(key, value);
map.put(key, fresh);
addNode(fresh);
count++;
} else {
node.value = value;
moveToHead(node);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
LeetCode146 instance = new LeetCode146(Integer.valueOf(scanner.nextLine()));
while (scanner.hasNextLine()) {
String command = scanner.nextLine().trim();
if (command.charAt(0) == 'p') {
int key = Integer.valueOf(command.substring(2, command.lastIndexOf(" ")));
int value = Integer.valueOf(command.substring(command.lastIndexOf(" ")+1));
instance.put(key, value);
}else {
int key = Integer.valueOf(command.substring(2));
System.out.println(instance.get(key));
}
}
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.