【LeetCode】设计题 design(共38题)

链接:https://leetcode.com/tag/design/

【146】LRU Cache

【155】Min Stack

【170】Two Sum III - Data structure design (2018年12月6日,周四)

Design and implement a TwoSum class. It should support the following operations: add and find.

add - Add the number to an internal data structure.
find - Find if there exists any pair of numbers which sum is equal to the value.

Example 1:
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
Example 2:
add(3); add(1); add(2);
find(3) -> true
find(6) -> false

题解:无

 class TwoSum {
public:
/** Initialize your data structure here. */
TwoSum() { } /** Add the number to an internal data structure.. */
void add(int number) {
nums.push_back(number);
mp[number]++;
} /** Find if there exists any pair of numbers which sum is equal to the value. */
bool find(int value) {
for (auto ele : nums) {
int target = value - ele;
if (mp.find(target) != mp.end()) {
if (target == ele && mp[target] >= || target != ele && mp[target] >= ) {
return true;
}
}
}
return false;
}
vector<int> nums;
unordered_map<int, int> mp;
}; /**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* bool param_2 = obj.find(value);
*/

【173】Binary Search Tree Iterator

【208】Implement Trie (Prefix Tree) (以前 trie 专题做过)

【211】Add and Search Word - Data structure design

【225】Implement Stack using Queues

【232】Implement Queue using Stacks

【244】Shortest Word Distance II (2019年2月12日)

Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.

Example:

Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”

Output: 3

Input: word1 = "makes", word2 = "coding"

Output: 1

题解:一个map存单词和对应的下标列表。然后二分查找。

 class WordDistance {
public:
WordDistance(vector<string> words) {
n = words.size();
for (int i = ; i < words.size(); ++i) {
mp[words[i]].push_back(i);
}
} int shortest(string word1, string word2) {
vector<int> & list1 = mp[word1], & list2 = mp[word2];
int res = n;
for (auto& e : list1) {
auto iter = upper_bound(list2.begin(), list2.end(), e);
if (iter != list2.end()) {
res = min(res, abs((*iter) - e));
}
if (iter != list2.begin()) {
--iter;
res = min(res, abs((*iter) - e));
}
}
return res;
}
unordered_map<string, vector<int>> mp;
int n;
}; /**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(words);
* int param_1 = obj.shortest(word1,word2);
*/

【251】Flatten 2D Vector

【281】Zigzag Iterator (2019年1月18日,学习什么是iterator)

给了两个一维数组,逐个返回他们的元素。

Example:
Input:
v1 = [1,2]
v2 = [3,4,5,6]
Output: [1,3,2,4,5,6]
Explanation: By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,3,2,4,5,6].

题解:什么是iterator,就是一个东西它有两个方法:(1)getNext(), (2) hasNext()

本题没有什么好说的,直接搞就行了。

 class ZigzagIterator {
public:
ZigzagIterator(vector<int>& v1, vector<int>& v2) {
n1 = v1.size();
n2 = v2.size();
this->v1 = v1, this->v2 = v2;
}
int next() {
if (p1 < n1 && p2 < n2) {
int ret = cur == ? v1[p1++] : v2[p2++];
cur = - cur;
return ret;
}
if (p1 < n1) {
return v1[p1++];
}
if (p2 < n2) {
return v2[p2++];
}
return -;
}
bool hasNext() {
return p1 < n1 || p2 < n2;
}
int cur = ;
int p1 = , p2 = , n1 = , n2 = ;
vector<int> v1, v2;
};
/**
* Your ZigzagIterator object will be instantiated and called as such:
* ZigzagIterator i(v1, v2);
* while (i.hasNext()) cout << i.next();
*/

【284】Peeking Iterator (2019年1月18日,学习什么是iterator)

给了一个 Iterator 的基类,实现 PeekIterator 这个类。它除了有 hashNext() 和 next() 方法之外还有一个方法叫做 peek(),能访问没有访问过的第一个元素,并且不让它pass。

题解:用两个变量保存 是不是有一个 peek 元素,peek元素是什么。每次调用peek方法的时候先查看当前缓存有没有这个元素,如果有的话就返回,如果没有的话,就调用 Iterator::next方法获取当前缓存。

 // Below is the interface for Iterator, which is already defined for you.
// **DO NOT** modify the interface for Iterator.
class Iterator {
struct Data;
Data* data;
public:
Iterator(const vector<int>& nums);
Iterator(const Iterator& iter);
virtual ~Iterator();
// Returns the next element in the iteration.
int next();
// Returns true if the iteration has more elements.
bool hasNext() const;
}; class PeekingIterator : public Iterator {
public:
PeekingIterator(const vector<int>& nums) : Iterator(nums) {
// Initialize any member here.
// **DO NOT** save a copy of nums and manipulate it directly.
// You should only use the Iterator interface methods. } // Returns the next element in the iteration without advancing the iterator.
int peek() {
if (hasPeeked) {
return peekElement;
}
peekElement = Iterator::next();
hasPeeked = true;
return peekElement;
} // hasNext() and next() should behave the same as in the Iterator interface.
// Override them if needed.
int next() {
if (hasPeeked) {
hasPeeked = false;
return peekElement;
}
return Iterator::next();
} bool hasNext() const {
if (hasPeeked || Iterator::hasNext()) {
return true;
}
return false;
}
bool hasPeeked = false;
int peekElement; };

【288】Unique Word Abbreviation

【295】Find Median from Data Stream

【297】Serialize and Deserialize Binary Tree

【341】Flatten Nested List Iterator

【346】Moving Average from Data Stream

【348】Design Tic-Tac-Toe

【353】Design Snake Game

【355】Design Twitter

【359】Logger Rate Limiter (2019年3月13日,周三)

Design a logger system that receive stream of messages along with its timestamps, each message should be printed if and only if it is not printed in the last 10 seconds.

主要就是实现这个 bool shouldPrintMessage(int timestamp, string message) 接口。

题解:用一个 map 做 cache。

 class Logger {
public:
/** Initialize your data structure here. */
Logger() { }
/** Returns true if the message should be printed in the given timestamp, otherwise returns false.
If this method returns false, the message will not be printed.
The timestamp is in seconds granularity. */
bool shouldPrintMessage(int timestamp, string message) {
if (cache.count(message)) {
if (timestamp - cache[message] < ) {return false;}
}
cache[message] = timestamp;
return true;
}
unordered_map<string, int> cache;
}; /**
* Your Logger object will be instantiated and called as such:
* Logger obj = new Logger();
* bool param_1 = obj.shouldPrintMessage(timestamp,message);
*/

【362】Design Hit Counter(2019年2月21日, 周四)

Design Hit Counter which counts the number of hits received in the past 5 minutes.

实现一个类: 主要实现两个方法

HitCounter counter = new HitCounter();

void hit(int timestamp); // hit at ts

int getHits(int timestamp); //get how many hits in past 5 minutes.

 class HitCounter {
public:
/** Initialize your data structure here. */
HitCounter() { } /** Record a hit.
@param timestamp - The current timestamp (in seconds granularity). */
void hit(int timestamp) {
while (!que.empty() && que.front() + TIMEGAP <= timestamp) {
que.pop();
}
que.push(timestamp);
} /** Return the number of hits in the past 5 minutes.
@param timestamp - The current timestamp (in seconds granularity). */
int getHits(int timestamp) {
while (!que.empty() && que.front() + TIMEGAP <= timestamp) {
que.pop();
}
return que.size();
}
queue<int> que;
const int TIMEGAP = ;
}; /**
* Your HitCounter object will be instantiated and called as such:
* HitCounter obj = new HitCounter();
* obj.hit(timestamp);
* int param_2 = obj.getHits(timestamp);
*/

【379】Design Phone Directory (2019年2月21日,周四)

设计一个电话目录有如下三个功能:

  1. get: Provide a number which is not assigned to anyone.
  2. check: Check if a number is available or not.
  3. release: Recycle or release a number

题解:我用了一个set,一个queue来实现的。set来存储使用过的电话号码。使用queue来存储删除后的电话号码,如果当前queue为空的话,我们就用 curNumber 生成一个新的电话号码。

复杂度分析如下:get: O(logN), check: O(1), release: O(1), beats 80%.

 class PhoneDirectory {
public:
/** Initialize your data structure here
@param maxNumbers - The maximum numbers that can be stored in the phone directory. */
PhoneDirectory(int maxNumbers) {
this->maxNumbers = maxNumbers;
} /** Provide a number which is not assigned to anyone.
@return - Return an available number. Return -1 if none is available. */
int get() {
if (que.empty()) {
if (curNumber == maxNumbers) {
return -;
}
usedNumbers.insert(curNumber);
return curNumber++;
}
int number = que.front();
usedNumbers.insert(number);
que.pop();
return number;
} /** Check if a number is available or not. */
bool check(int number) {
if (usedNumbers.find(number) != usedNumbers.end()) {
return false;
}
return true;
} /** Recycle or release a number. */
void release(int number) {
if (usedNumbers.find(number) == usedNumbers.end()) {return;}
usedNumbers.erase(number);
que.push(number);
}
int maxNumbers;
unordered_set<int> usedNumbers;
int curNumber = ;
queue<int> que;
}; /**
* Your PhoneDirectory object will be instantiated and called as such:
* PhoneDirectory obj = new PhoneDirectory(maxNumbers);
* int param_1 = obj.get();
* bool param_2 = obj.check(number);
* obj.release(number);
*/

【380】Insert Delete GetRandom O(1)

【381】Insert Delete GetRandom O(1) - Duplicates allowed

【432】All O`one Data Structure

【460】LFU Cache

【588】Design In-Memory File System

【604】Design Compressed String Iterator

【622】Design Circular Queue (2018年12月12日,算法群,用数组实现队列)

设计用数组实现节省空间的环形队列。

题解:用个size来标记现在队列里面有几个元素,(不要用rear和front的关系来判断,不然一大一小还有环非常容易出错)。

 class MyCircularQueue {
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
que.resize(k);
capacity = k;
front = rear = ;
size = ;
} /** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if (size == capacity) {return false;}
++size;
rear = rear % capacity;
que[rear++] = value;
return true;
} /** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if (size == ) {return false;}
--size;
front = (front + ) % capacity;
return true;
} /** Get the front item from the queue. */
int Front() {
if (size == ) {return -;}
return que[front];
} /** Get the last item from the queue. */
int Rear() {
if (size == ) {return -;}
rear = rear % capacity;
return rear == ? que[capacity-] : que[rear-];
} /** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return size == ;
} /** Checks whether the circular queue is full or not. */
bool isFull() {
return size == capacity;
}
int front, rear, size, capacity;
vector<int> que;
}; /**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue* obj = new MyCircularQueue(k);
* bool param_1 = obj->enQueue(value);
* bool param_2 = obj->deQueue();
* int param_3 = obj->Front();
* int param_4 = obj->Rear();
* bool param_5 = obj->isEmpty();
* bool param_6 = obj->isFull();
*/

【631】Design Excel Sum Formula

【635】Design Log Storage System

【641】Design Circular Deque

【642】Design Search Autocomplete System

【705】Design HashSet

【706】Design HashMap

【707】Design Linked List

【716】Max Stack (2019年1月19日,谷歌决战复习,2 stacks || treemap + double linked list)

设计一个栈,能实现栈的基本操作,push 和 pop,并且能返回栈中的最大元素,还能弹出栈中的最大元素。

题解:我能想到 2 stack 的方法。和155题一样的。

 class MaxStack {
public:
/** initialize your data structure here. */
MaxStack() { } void push(int x) {
stk.push(x);
if (maxStk.empty()) {
maxStk.push(x);
} else {
maxStk.push(max(x, peekMax()));
}
} int pop() {
int ret = stk.top();
stk.pop();
maxStk.pop();
return ret;
} int top() {
return stk.top();
} int peekMax() {
return maxStk.top();
} int popMax() {
stack<int> buffer;
int max = maxStk.top();
while (!stk.empty() && stk.top() != max) {
buffer.push(pop());
}
pop();
while (!buffer.empty()) {
push(buffer.top());
buffer.pop();
}
return max;
}
stack<int> stk, maxStk;
}; /**
* Your MaxStack object will be instantiated and called as such:
* MaxStack obj = new MaxStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.peekMax();
* int param_5 = obj.popMax();
*/

但是treemap方法是什么,似乎跟lru cache 类似。

上一篇:MySQL事务处理案例演示


下一篇:推荐两个很好用的javascript模板引擎