链接: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 类似。

【LeetCode】设计题 design(共38题)的更多相关文章

  1. 【LeetCode】贪心 greedy(共38题)

    [44]Wildcard Matching [45]Jump Game II (2018年11月28日,算法群衍生题) 题目背景和 55 一样的,问我能到达最后一个index的话,最少走几步. 题解: ...

  2. 【LeetCode】数学(共106题)

    [2]Add Two Numbers (2018年12月23日,review) 链表的高精度加法. 题解:链表专题:https://www.cnblogs.com/zhangwanying/p/979 ...

  3. 【LeetCode】树(共94题)

    [94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 ...

  4. 【LeetCode】BFS(共43题)

    [101]Symmetric Tree 判断一棵树是不是对称. 题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs. // 这个题目的重点是 比较 ...

  5. 【LeetCode】Recursion(共11题)

    链接:https://leetcode.com/tag/recursion/ 247 Strobogrammatic Number II (2019年2月22日,谷歌tag) 给了一个 n,给出长度为 ...

  6. Leetcode 简略题解 - 共567题

    Leetcode 简略题解 - 共567题     写在开头:我作为一个老实人,一向非常反感骗赞.收智商税两种行为.前几天看到不止两三位用户说自己辛苦写了干货,结果收藏数是点赞数的三倍有余,感觉自己的 ...

  7. LeetCode (85): Maximal Rectangle [含84题分析]

    链接: https://leetcode.com/problems/maximal-rectangle/ [描述] Given a 2D binary matrix filled with '0's ...

  8. 剑指offer 面试38题

    面试38题: 题:字符串的排列 题目:输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,ca ...

  9. Leetcode春季打卡活动 第二题:206. 反转链表

    Leetcode春季打卡活动 第二题:206. 反转链表 206. 反转链表 Talk is cheap . Show me the code . /** * Definition for singl ...

随机推荐

  1. 英语单词omitting

    omitting 来源——报错 [root@centos7 ~]# cp /etc/ /bin cp: omitting directory ‘/etc/’ [root@centos7 ~]# cp ...

  2. drf 的分页功能

    1 settings中配置 page_size = 20 代表每页20条数据 REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framewor ...

  3. 元素隐藏visibility:hidden与元素消失display:none的区别

    visibility属性用来确定元素是显示还是隐藏的,这用visibility="visible|hidden"来表示(visible表示显示,hidden表示隐藏). 当visi ...

  4. composer proc_open(): fork failed – Cannot allocate memory

    一般小的VPS 才1G内存,如果使用composer会提示内存不足的现象 解决办法,可以使用交换内存 直接命令 /bin/dd if=/dev/zero of=/var/swap.1 bs=1M co ...

  5. EZOJ #373排序

    分析 它居然真的是个nlog^3暴力?! 两个数在加小于min(lowbit(x),lowbit(y))的数时对他们的奇偶性不影响 因此每次加上min(lowbit(x),lowbit(y))判断此时 ...

  6. 前端工具-调试压缩后的JS(Source Map的使用)

    使用 Source Map 可以在 FF 的调试器. Chrome 的 Sources 和 VSCode 中给压缩前的文件下断点,也可以方便定位错误发生的位置(定位到压缩前的文件). 何为 Sourc ...

  7. leaflet-加载天地图-解决纬度偏移特别大

    这几天学习 leaflet 在加载天地图时将以前的接口拿来用结果偏差了特别大(差不多是 90 度),中国纬度到了 100 多,试了改变投影和 y 轴翻转的配置都不好使,最后上网搜索到了Leaflet. ...

  8. jenkins之定时任务配置

    jenkins可以配置任务定时执行 1.jenkins配置解释说明 在每个job的配置项里,有一个构建触发器配置,勾选“定时检查版本库选项”,在输入框可根据需求配置时间: 日程表填写格式: 日程表(S ...

  9. ag-grid 表格中添加图片

    ag-grid是一种非常好用的表格,网上搜索会有各种各样的基本用法,不过对于在ag-grid 表格中添加图片我没有找到方法,看了官方的文档,当然英文的自己也是靠网页翻译,最后发现有这么一个例子,我知道 ...

  10. MySQL-- 数据库的三范式

    目前关系数据库有六种范式:第一范式(1NF).第二范式(2NF).第三范式(3NF).巴斯-科德范式(BCNF).第四范式(4NF)和第五范式(5NF,又称完美范式). 而通常我们用的最多的就是第一范 ...