沙雕题解:
import java.util.*;
public class Solution {
int capacity;
HashMap<Integer,Node> hashmap;
Node head;
Node tail;
public class Node{
Node left;
Integer key;
Integer value;
Node right;
public Node(Integer key, Integer value) {
this.left = null;
this.key = key;
this.value = value;
this.right = null;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public Integer getKey() {
return key;
}
public void setKey(Integer key) {
this.key = key;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
public Solution(int capacity){
hashmap = new HashMap<>(capacity);
this.capacity = capacity;
}
public int get(int key) {
// write code here
if (hashmap.containsKey(key)){
int value = hashmap.get(key).getValue();
if (hashmap.get(key) == tail && (head != tail)){
tail = tail.getLeft();
tail.setRight(null);
hashmap.get(key).setLeft(null);
hashmap.remove(key);
set(key,value);
} else if(hashmap.get(key) == head && (head != tail)){
set(key,value);
} else if (head != tail){
Node node = hashmap.get(key);
node.getLeft().setRight(node.getRight());
node.getRight().setLeft(node.getLeft());
node.setLeft(null);
node.setRight(null);
hashmap.remove(key);
set(key,value);
}
return head.getValue();
} else {
return -1;
}
}
public void set(int key, int value) {
// write code here
if (hashmap.containsKey(key)){
if (hashmap.get(key) == tail && (head != tail)){
tail = tail.getLeft();
tail.setRight(null);
hashmap.get(key).setLeft(null);
hashmap.remove(key);
set(key,value);
} else if(hashmap.get(key) == head && (head != tail)){
head = head.getRight();
head.setLeft(null);
hashmap.get(key).setLeft(null);
hashmap.remove(key);
set(key,value);
} else if (head != tail){
Node node = hashmap.get(key);
node.getLeft().setRight(node.getRight());
node.getRight().setLeft(node.getLeft());
node.setLeft(null);
node.setRight(null);
hashmap.remove(key);
set(key,value);
} else{
hashmap.get(key).setValue(value);
}
} else {
if (hashmap.size() == capacity) {
tail = tail.getLeft();
hashmap.remove(tail.getRight().getKey());
}
Node node = new Node(key, value);
if (head == null) {
head = node;
tail = node;
} else {
head.setLeft(node);
node.setRight(head);
head = node;
}
hashmap.put(key, node);
}
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution solution = new Solution(capacity);
* int output = solution.get(key);
* solution.set(key,value);
*/