LeetCode Design
题解
146 LRU Cache
- Double linked list + hashmap.
|
|
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.
Linked Mentions
-
No backlinks found.