题解

146 LRU Cache

  • Double linked list + hashmap.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
class DoubleListNode {
public:
    int key;
    int value;
    DoubleListNode* next;
    DoubleListNode* prev;
    DoubleListNode(int k, int val) {
        key = k;
        value = val;
        next = nullptr;
        prev = nullptr;
    }
};

class LRUCache {
public:
    unordered_map<int, DoubleListNode*> dict;
    DoubleListNode* head;
    DoubleListNode* tail;

    int cap;
    int size;

    LRUCache(int capacity) {
        cap = capacity;
        size = 0;

        head = new DoubleListNode(-1, -1);
        tail = new DoubleListNode(-1, -1);

        head->next = tail;
        tail->prev = head;
    }

    int get(int key) {
        if (dict.count(key)) {
            DoubleListNode* node = dict[key];
            moveNodeToHead(node);
            return node->value;
        }
        return -1;
    }

    void put(int key, int value) {
        if (dict.count(key)) {
            DoubleListNode* node = dict[key];
            node->value = value;
            moveNodeToHead(node);
        } else {
            DoubleListNode* newNode = new DoubleListNode(key, value);
            insertHead(newNode);
            dict[key] = newNode;
            size++;

            if (size > cap) {
                DoubleListNode* node = tail->prev;

                removeNode(node);
                dict.erase(node->key);
                delete node;
                size--;
            }
        }
    }

    void moveNodeToHead(DoubleListNode* node) {
        removeNode(node);
        insertHead(node);
    }

    void removeNode(DoubleListNode* node) {
        DoubleListNode* prev = node->prev;
        DoubleListNode* next = node->next;

        prev->next = next;
        next->prev = prev;
    }

    void insertHead(DoubleListNode* newNode) {
        DoubleListNode* next = head->next;
        newNode->prev = head;
        head->next = newNode;
        newNode->next = next;
        next->prev = newNode;
    }

};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */

244 Shortest Word Distance II

  • Given word list and two words, find minimum distance of their indices. There might be many queries.
  • O(n) time and space with hashmap and merge list.

251 Flatten 2D Vector

  • hasNext and next on a 2D vector.

271 Encode and Decode Strings

281 Zigzag Iterator

  • Given two number lists, the iterator should return their elements alternatively.

284 Peeking Iterator

  • Create a temporary iterator and find its next.
  • Cache next element.

288 Unique Word Abbreviation

341 Flatten Nested List Iterator

  • hasNext and next. Use stack to store iterators.

346 Moving Average from Data Stream

348 Design Tic-Tac-Toe

  • O(1) time for each move and O(n) space. Save rowCount, colCount and crossCount.

353 Design Snake Game

362 Design Hit Counter

  • hit(timestamp), getHits(<=timestamp). Only 5-minute valid interval.
  • O(1) time for both operations. Use prefix counts and deleted counts.

379 Design Phone Directory

  • get(), check(), release() on an array.
  • Use a heap pointer and a free list.

380 Insert Delete GetRandom O(1)

  • Swap deleted one with the last one.

381 Insert Delete GetRandom O(1) - Duplicates allowed

  • Keep a set of indices instead of a single index.

432 All O`one Data Structure

  • Inc(key), Dec(key), GetMaxKey(), GetMinKey().

460 LFU Cache

  • Use double linked-list for frequency list and recent list. Each frequency list node contains a recent list.
  • push_front for frequency-list put new key, earse for get key, insert for frequency list change. Use get in put to add frequency.

535 Encode and Decode TinyURL

  • Use (26+26+10)-base number.

622 Design Circular Queue

635 Design Log Storage System

  • Given logs coming in timestamp order, support storage and range query by different granularity.
  • Use trie, maintain isUpperBound and isLowerBound.

855 Exam Room

  • Implement seat() and leave() for a row of chairs. seat() will choose the seat that maximize the distance to others.
  • Maintain intervals sorted by maximum distance possible for seat() and by left end for leave().

981 Time Based Key-Value Store

  • Design a key-value store, supporting read latest value before some timestamp.
  • O(1) set and O(log(n)) read. use map’s lower_bound to search timestamp.