上岸核心算法题
  • Catalog
  • 基础题
  • 核心算法200题
    • Sort Algorithms
      • MergeSort
      • Merge Two Sorted Array
      • QuickSort
      • Sort Integers II
      • Partition Array
      • N Car Fleet
      • Reverse Pairs
      • Sort Colors
      • Sort Colors II
      • Subarray Sum closest
      • Merge k Sorted Lists
      • Sort List
    • Binary Search
      • Last Position of Target
      • Positive Product
      • Guess Number Higher or Lower
      • Find Minimum in Rotated Sorted Array
      • Find Minimum in Rotated Sorted Array II
      • Kth Smallest Element in a Sorted Matrix
      • Search a 2D Matrix
      • Maximum Number in Mountain Sequence
      • Find K Closest Elements
      • Search in a Big Sorted Array
      • Fast Power
      • Find Peak Element
      • First Bad Version
      • Search in Rotated Sorted Array
      • add two numbers II
    • LinkedList
      • Reverse Linked List
      • Remove Duplicates from Sorted List
      • Remove Duplicates from Sorted List
      • Merge Two Sorted List
      • Intersection of Two Linked Lists
      • Add Two Numbers
    • List & Queue & Stack
      • Min Stack
      • Evaluate Reverse Polish Notation
      • Convert Expression to Reverse Polish Notation
    • Hashmap & Heap
      • Kth Largest Element in an Array
      • Missing Number
      • Ugly Number II
      • Implement Queue by Two Stack
      • Merge K Sorted Lists
      • Top k Largest Numbers
      • K Closest Points
      • Insert Delete GetRandom O(1)
      • First Unique Character in a String
      • Implement Stack by Two Queues
      • Moving Average from Data Stream
    • Two Pointers
      • Remove duplicates from adjacent/sorted array
      • Reverse String
      • Reverse String II
      • Reverse Words in a String
      • String shift/rotate
      • Reverse Words in a String III
      • Implement strStr()
      • Palindrome Number
      • Valid Palindrome
      • Valid Anagram
      • Kth Largest Element
      • Partition Array
      • 3Sum
      • Sort Colors II
      • Two Sum II - Input array is sorted
      • Sort Integers II
      • Remove Duplicate Numbers in Array
      • Move Zeroes
      • Two Sum III - Data structure design
      • Middle of Linked List
    • BIT Operation & Math
      • Single Number
    • Data Structure
      • First Unique Number in Data Stream
      • Sliding Window
      • Animal Shelter
      • Linked List Cycle II
      • Convert Expression to Reverse Polish Notation
      • Expression Tree Build
    • Binary Tree Divide & Conquer
      • Binary Search Tree Iterator
      • Binary Tree Preorder Traversal
      • Binary Tree Inorder Traversal
      • Symmetric Tree
      • Invert Binary Tree
      • Search Range in Binary Search Tree
      • Largest BST Subtree
      • Lowest Common Ancestor of a Binary Search Tree
      • Lowest Common Ancestor of a Binary Tree
      • BST Node Distance
      • Maximum Width if Binary Tree
      • Construct Binary Tree from Preorder and Inorder Traversal
      • Maximum Depth of Binary Tree
      • Closest Binary Search Tree Value
      • Closest Binary Search Tree Value II
      • Validate Binary Search Tree
      • Lowest Common Ancestor III
      • Kth Smallest Element in a BST
      • Balanced Binary Tree
      • Flatten Binary Tree to Linked List
      • Binary Tree Paths
      • Minimum Subtree
      • Vertical Order Traversal of a Binary Tree
    • BFS
      • Binary Tree
        • Check full binary tree
        • Serialize and Deserialize Binary Tree
        • Graph Valid Tree
        • Check Completeness of a Binary Tree
        • Binary Tree Zigzag Level Order Traversal
        • Binary Tree Level Order Traversal
      • Graph
        • Word Ladder
        • Connected Component in Undirected Graph
        • Open the Lock
        • Clone Graph
        • Search Graph Nodes
        • Course Schedule II
        • Course Schedule
        • Topological Sorting
        • Binary Tree Maximum Path Sum II
        • Shortest Distance from All Buildings
        • Shortest Path in Undirected Graph
        • 八数码问题 Sliding Puzzle II
        • Pacific Atlantic Water Flow
      • Matrix
        • Sequence Reconstruction
        • Knight Shortest Path
        • Knight Shortest Path II
        • Number of Islands
        • Walls and Gates
        • Surrounded Regions
        • Zombie in Matrix
        • Build Post Office II
    • DFS
      • 组合型DFS
        • Letter Combinations of a Phone Number
        • Palindrome Partitioning
        • Split String
        • Generate Parentheses
        • k Sum II
        • Combination Sum IV
        • Combination Sum III
        • Combination Sum II
        • Combination Sum
        • Subsets II
        • Subsets
      • 排列型DFS
        • Permutations
        • Permutations II
        • N-Queens
        • Robot Room Cleaner
      • 剪枝优化
        • Word Pattern II
        • Word Ladder II
    • Memorization search & Dynamic Programming
      • Regular Expression Matching
      • Wildcard Matching
      • Word Break II
      • Word Break
      • Triangle
      • Word Break III
    • Basic Dynamic Programming & Coordinate Dynamic Programming
      • Backpack Problem
        • Backpack
        • Backpack V
        • Backpack II
        • Combination Sum IV (Backpack VI
        • Decode Ways
        • Decode Ways II
      • Coordinate Dynamic Programming
        • Sparse Matrix Multiplication
        • Maximum Submatrix
        • Knight Shortest Path
        • Unique Paths II
        • Unique Paths
        • Minimum Path Sum
        • knight Shortest Path II
        • Distinct Subsequences
        • Paint House
      • Sequential Dynamic Programmin
        • Triangle
        • Longest Increasing Subsequence
        • Number of Longest Increasing Subsequenc
        • Jump Game
        • Jump Game II
        • Best Time to buy and sell
        • Best Time to buy and sell II
      • Median of two Sorted Arrays
      • Median of K Sorted Arrays
      • Merge K Sorted Arrays
      • Merge K Sorted Interval Lists
      • Range Sum Query - Mutable
      • Maximum Subarray
      • Merge Sorted Array
      • Subarray Sum
      • Intersection of Two Arrays
      • Merge Two Sorted Interval Lists
      • Russian Doll Envelopes
      • Largest Divisible Subset
      • Climbing Stairs
    • Other kinds of Problems
      • LRU
      • Longest Palindromic Substring
      • Valid Palindrome
      • Implement strStr()
      • Longest Palindrome
  • 进阶算法200题
由 GitBook 提供支持
在本页

这有帮助吗?

  1. 核心算法200题
  2. Other kinds of Problems

LRU

  • 常规写法

public class LRUCache {
    private class Node{
        Node prev;
        Node next;
        int key;
        int value;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
            this.prev = null;
            this.next = null;
        }
    }

    private int capacity;
    private HashMap<Integer, Node> hs = new HashMap<Integer, Node>();
    private Node head = new Node(-1, -1);
    private Node tail = new Node(-1, -1);

    public LRUCache(int capacity) {
        this.capacity = capacity;
        tail.prev = head;
        head.next = tail;
    }

    public int get(int key) {
        if( !hs.containsKey(key)) {    		//key找不到
            return -1;
        }

        // remove current
        Node current = hs.get(key);
        current.prev.next = current.next;
        current.next.prev = current.prev;

        // move current to tail
        move_to_tail(current);			//每次get,使用次数+1,最近使用,放于尾部

        return hs.get(key).value;
    }

    public void set(int key, int value) {			//数据放入缓存
        // get 这个方法会把key挪到最末端,因此,不需要再调用 move_to_tail
        if (get(key) != -1) {
            hs.get(key).value = value;
            return;
        }

        if (hs.size() == capacity) {		//超出缓存上限
            hs.remove(head.next.key);		//删除头部数据
            head.next = head.next.next;
            head.next.prev = head;
        }

        Node insert = new Node(key, value);		//新建节点
        hs.put(key, insert);
        move_to_tail(insert);					//放于尾部
    }

    private void move_to_tail(Node current) {    //移动数据至尾部
        current.prev = tail.prev;
        tail.prev = current;
        current.prev.next = current;
        current.next = tail;
    }
}
class LinkedListNode(object):
    def __init__(self, key=None, val=-1):
        self.key = key
        self.val = val
        self.pre = None
        self.next = None


class LinkedList(object):
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0

    def appendHead(self, node):
        node.next, node.pre = self.head, None
        if self.head:
            self.head.pre = node
        self.head = node

        if not self.tail:
            self.tail = self.head

        self.size += 1

    def remove(self, node):
        if not node:
            return

        pre, next = node.pre, node.next
        if pre:
            pre.next = next
        if next:
            next.pre = pre

        if self.head == node:
            self.head = next

        if self.tail == node:
            self.tail = pre

        self.size -= 1
        return node

    def removeTail(self):
        return self.remove(self.tail)

    def advance(self, node):
        self.remove(node)
        self.appendHead(node)


class LRUCache(object):
    def __init__(self, capacity):
        self.capacity = capacity
        self.record = {}
        self.linkedList = LinkedList()

    def get(self, key):
        if key not in self.record:
            return -1

        self.linkedList.advance(self.record[key])
        return self.record[key].val

    def set(self, key, value):
        if key not in self.record:
            node = LinkedListNode(key, value)

            self.linkedList.appendHead(node)
            self.record[key] = node

            if self.linkedList.size > self.capacity:
                del self.record[self.linkedList.removeTail().key]
        else:
            self.record[key].val = value
            self.linkedList.advance(self.record[key])
  • LinkedHashMap

class LRUCache {
    private int capacity;
    private Map<Integer, Integer> map;
    public LRUCache(int capacity) {
        this.capacity = capacity;
        map = new LinkedHashMap<>();
    }
    
    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        int val = map.get(key);
        map.remove(key);
        map.put(key, val);
        return val;
    }
    
    public void put(int key, int value) {
        if (map.containsKey(key)) {
            map.put(key, value);
            get(key);
            return;
        }
        map.put(key, value);
        if (map.size() > capacity) {
            int victim = map.entrySet().iterator().next().getKey();
            map.remove(victim);
        }
    }
}
class LRUCache:

    # @param capacity, an integer
    def __init__(self, capacity):
        self.capacity = capacity
        self.cache = collections.OrderedDict()

    # @return an integer
    def get(self, key):
        if not key in self.cache:
            return -1
        value = self.cache.pop(key)
        self.cache[key] = value
        return value

    # @param key, an integer
    # @param value, an integer
    # @return nothing
    def set(self, key, value):
        if key in self.cache:
            self.cache.pop(key)
        elif len(self.cache) == self.capacity:
            self.cache.popitem(last=False)
        self.cache[key] = value
上一页Other kinds of Problems下一页Longest Palindromic Substring

最后更新于5年前

这有帮助吗?