LRU Cache
★★☆☆☆
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1. set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
import java.util.LinkedHashMap;
public class LRUCache {
private Map<Integer, Integer> map;
public LRUCache(int capacity) {
map = new LinkedHashMap<Integer, Integer>(16, 0.75f, true) {
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > capacity;
}
};
}
public int get(int key) {
return map.getOrDefault(key, -1);
}
public void set(int key, int value) {
map.put(key,value);
}
}
Implement Queue using Stacks
★★☆☆☆
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
solution by Stephen
- "When I need to peek/pop but the output stack is empty, I move all elements from input to output stack, thereby reversing the order so it's the correct order for peek/pop."
class myQueue {
Stack<Integer> input = new Stack();
Stack<Integer> output = new Stack();
// Push element x to the back of queue.
public void push(int x) {
input.push(x);
}
// Removes the element from in front of queue.
public void pop() {
peek();
output.pop();
}
// Get the front element.
public int peek() {
if (output.isEmpty()) {
while (!input.isEmpty())
output.push(input.pop());
}
return output.peek();
}
// Return whether the queue is empty.
public boolean empty() {
return input.isEmpty() && output.isEmpty();
}
}
Implement Stack using Queues
★★☆☆☆
Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
class MyStack {
// Push element x onto stack.
Queue<Integer> queue = new LinkedList<Integer>();
public void push(int x) {
queue.add(x);
for (int i = 0; i < queue.size() - 1; ++i) {
queue.add(queue.poll());
}
}
// Removes the element on top of the stack.
public void pop() {
queue.remove();
}
// Get the top element.
public int top() {
return queue.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}