Data Structure and Algorithms
  • Introduction
  • 面经
    • 亚马逊面经
  • Sorting
    • Quick Sort
    • Merge Sort
    • Heap Sort
  • Palindrome
    • Check String Palindrom
    • Palindrome Partitioning
    • Palindrome Partitioning II
    • Longest Palindromic Substring
    • Valid Palindrome
  • Linked List
    • Remove Duplicates from Sorted List
    • Remove Duplicates from Sorted List II
    • Remove Nth Node From End of List
    • Remove Linked List Elements
    • Remove Duplicates from Unsorted List
    • Remove duplicate Circular Linked list
    • Reverse Linked List
    • Reverse Linked List II
    • Reverse Nodes in k-Group
    • Partition List
    • Insertion Sort List
    • Reorder List
    • Linked List Cycle
    • Rotate List
    • Merge k Sorted Lists
    • Copy List with Random Pointer
    • Nth to Last Node in List
    • Add Two Numbers
    • Add Two Numbers II
    • Palindrome Linked List
  • Binary Search
    • Sqrt(x)
    • Search a 2D Matrix
    • Search a 2D Matrix II
    • Search Insert Position
    • First Position of Target
    • Last Position of Target
    • Count of Smaller Number
    • Search for a Range
    • Search in a Big Sorted Array
    • First Bad Version
    • Find Minimum in Rotated Sorted Array
    • Find Minimum in Rotated Sorted Array II
    • Search in Rotated Sorted Array
    • Search in Rotated Sorted Array II
    • Find Peak Element*
    • Recover Rotated Sorted Array
    • Rotate String
    • Wood Cut
    • Total Occurrence of Target
    • Closest Number in Sorted Array
    • K Closest Number in Sorted Array
    • Maximum Number in Mountain Sequence
    • Search Insert Position *
    • Pow(x, n)
    • Divide Two Integers
  • Graph
    • Clone Graph
    • Topological Sorting
    • Permutations
    • Permutations II
    • Subsets
    • Subsets II
    • Word Ladder
    • Word Ladder II
    • N-Queens
    • N-Queens II
    • Connected Component in Undirected Graph
    • Six Degrees
    • String Permutation II
    • Letter Case Permutation
  • Data Structure
    • Min Stack
    • Implement a Queue by Two Stacks
    • Largest Rectangle in Histogram
    • Max Tree
    • Rehashing
    • LRU Cache
    • Subarray Sum
    • Anagrams
    • Longest Consecutive Sequence
    • Data Stream Median
    • Heapify
    • Ugly Number
    • Ugly Number II
  • Misc
    • PlaceHolder
    • Fibonacci
  • Array and Numbers
    • Merge Sorted Array
    • Merge Two Sorted Arrays
    • Median of two Sorted Arrays
    • Best Time to Buy and Sell Stock
    • Best Time to Buy and Sell Stock II
    • Best Time to Buy and Sell Stock III
    • Maximum Subarray
    • Maximum Subarray II
    • Maximum Subarray III
    • Minimum Subarray
    • Maximum Subarray Difference
    • Subarray Sum
    • Subarray Sum Closest
    • Two Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum
    • k Sum
    • k Sum II
    • Partition Array
    • Sort Letters by Case
    • Sort Colors
    • Sort Colors II
    • Interleaving Positive and Negative Numbers
    • Spiral Matrix
    • Spiral Matrix II
    • Rotate Image
  • Dynamic Programming I
    • Triangle
    • Minimum Path Sum
    • Unique Paths
    • Unique Paths II
    • Climbing Stairs
    • Jump Game
    • Jump Game II
    • 01 Matrix
    • Longest Line of Consecutive One in Matrix
    • Shortest Path in Binary Matrix
  • Dynamic Programming II
    • Word Break
    • Longest Common Subsequence
    • Longest Common Substring
    • Edit Distance
    • Distinct Subsequences
    • Interleaving String
    • k Sum
  • Binary Tree And Divide Conquer
    • Binary Tree Preorder Traversal*
    • Binary Tree Inorder Traversal*
    • Binary Tree Postorder Traversal*
    • Maximum Depth of Binary Tree
    • Minimum Depth of Binary Tree
    • Balanced Binary Tree
    • Lowest Common Ancestor
    • Binary Tree Maximum Path Sum
    • Binary Tree Maximum Path Sum II
    • Binary Tree Level Order Traversal*
    • Binary Tree Level Order Traversal II
    • Binary Tree Zigzag Level Order Traversal
    • Validate Binary Search Tree
    • Inorder Successor in Binary Search Tree
    • Binary Search Tree Iterator
    • Search Range in Binary Search Tree
    • Insert Node in a Binary Search Tree
    • Remove Node in Binary Search Tree
    • Find the kth largest element in the BST
    • Kth Smallest Element in a BST
    • Serialize and Deserialize Binary Tree*
    • Construct Binary Tree from Preorder and Inorder Traversal
    • Convert Sorted Array to Binary Search Tree
    • Unique Binary Search Trees *
    • Unique Binary Search Trees II *
    • Recover Binary Search Tree
    • Same Tree
    • Symmetric Tree
    • Path Sum*
    • Path Sum II*
    • Flatten Binary Tree to Linked List
    • Populating Next Right Pointers in Each Node
    • Sum Root to Leaf Numbers
    • Binary Tree Right Side View
    • Count Complete Tree Nodes
    • Invert Binary Tree
    • Binary Tree Paths*
    • Subtree of Another Tree
  • A家面试总结
  • Expedia面经收集
  • Python 常用语句
  • lotusflare
  • Microsoft
  • 模板
  • Bing 组面试总结
  • 面试笔记
  • Sliding window
Powered by GitBook
On this page

Was this helpful?

  1. Data Structure

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.

Solution:

LRU(very offen)

Least Recently Used

it's using the data structure 'Double LinkedList + HashMap'

(1)双向链表插入删除效率高(单向链表插入和删除时,还要查找节点的前节点)

(2)哈希表保存每个节点的地址,可以基本保证在O(1)时间内查找节点

When do Get:

if the key is there then delete the duplicate key from Linked List and move it to tail eventually the has table is no change but the dulplicated key will only pointed to the value which is tail and have null node.

when do set

if the key is there then delete the duplicate key then do insert.

LFU

Least Frequently Used

class DoublelyLinkedList:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.prev = self.next = None #made mistake to put as parameters

class LRUCache:

    # @param capacity, an integer
    def __init__(self, capacity):
        self.capacity = capacity
        self.hashmap = {}
        # double dummy head and tail pointer

        self.head = DoublelyLinkedList(-1, -1)
        self.tail = DoublelyLinkedList(-1, -1)

        self.tail.prev = self.head
        self.head.next = self.tail

    # @return an integer
    def get(self, key):
        # write your code here
        if key not in self.hashmap:
            return -1
        #remove the exsiting node and take advantage from dobuledLinkedList
        current = self.hashmap[key] 
        current.prev.next = current.next
        current.next.prev = current.prev
        #add the current node to the tail
        self.addNodeToTail(current)
        # return value
        return self.hashmap[key].value

    # @param key, an integer
    # @param value, an integer
    # @return nothing
    def set(self, key, value):
        # write your code here
        # check if the key exist before insert 
        if self.get(key) != -1:
            self.hashmap[key].value = value
            return
        if len(self.hashmap) >= self.capacity:
            self.hashmap.pop(self.head.next.key) # forget pop node from hashmap
            # the first node is dummy, we will remove the second
            self.head.next = self.head.next.next
            self.head.next.prev = self.head  # delete next node. 

        inserNode = DoublelyLinkedList(key, value)
        self.hashmap[key] = inserNode
        self.addNodeToTail(inserNode)

    def addNodeToTail(self, current):
        current.prev = self.tail.prev
        self.tail.prev = current
        current.prev.next = current
        current.next = self.tail
PreviousRehashingNextSubarray Sum

Last updated 4 years ago

Was this helpful?