最小栈

设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。
push(x) — 将元素 x 推入栈中。
pop() — 删除栈顶的元素。
top() — 获取栈顶元素。
getMin() — 检索栈中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); —> 返回 -3.
minStack.pop();
minStack.top(); —> 返回 0.
minStack.getMin(); —> 返回 -2.

解法

两个栈,一个正常存储,一个存储最小值,和剑指offer上的是一样的,更细节的可以去看一下。

AC代码

  1. class MinStack {
  2. public:
  3. /** initialize your data structure here. */
  4. MinStack() {}
  5. void push(int x) {
  6. s1.push(x);
  7. if (s2.empty() || x <= s2.top()) s2.push(x);
  8. }
  9. void pop() {
  10. if (s1.top() == s2.top()) s2.pop();
  11. s1.pop();
  12. }
  13. int top() {
  14. return s1.top();
  15. }
  16. int getMin() {
  17. return s2.top();
  18. }
  19. private:
  20. stack<int> s1, s2;
  21. };

LRU缓存机制

运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。
获取数据 get(key) - 如果密钥 (key) 存在于缓存中,则获取密钥的值(总是正数),否则返回 -1。 写入数据 put(key, value) - 如果密钥不存在,则写入其数据值。当缓存容量达到上限时,它应该在写入新数据之前删除最近最少使用的数据值,从而为新的数据值留出空间。
进阶:
你是否可以在 O(1) 时间复杂度内完成这两种操作?
示例:
LRUCache cache = new LRUCache( 2 / 缓存容量 / );
cache.put(1, 1);
cache.put(2, 2);
cache.get(1); // 返回 1
cache.put(3, 3); // 该操作会使得密钥 2 作废
cache.get(2); // 返回 -1 (未找到)
cache.put(4, 4); // 该操作会使得密钥 1 作废
cache.get(1); // 返回 -1 (未找到)
cache.get(3); // 返回 3
cache.get(4); // 返回 4

解法

按题意的来嘛,用 Map 加 Stack 就可以解决了。

AC代码

  1. /**
  2. * Your LRUCache object will be instantiated and called as such:
  3. * LRUCache obj = new LRUCache(capacity);
  4. * int param_1 = obj.get(key);
  5. * obj.put(key,value);
  6. */
  7. class LRUCache {
  8. Map<Integer,Integer> map ;
  9. Stack<Integer> stack;
  10. int size;
  11. public LRUCache(int capacity) {
  12. stack = new Stack<>();
  13. map = new HashMap<>(capacity);
  14. size = capacity;
  15. }
  16. public int get(int key) {
  17. if(!stack.contains(key)){
  18. return -1;
  19. }
  20. boolean flag = stack.remove(Integer.valueOf(key));
  21. stack.push(key);
  22. return map.get(key);
  23. }
  24. public void put(int key, int value) {
  25. if(stack.contains(key)){
  26. stack.remove(Integer.valueOf(key));
  27. }else{
  28. if(stack.size() == size){
  29. int count = stack.remove(0);
  30. map.remove(count);
  31. }
  32. }
  33. stack.push(key);
  34. map.put(key,value);
  35. }
  36. }