【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日,周四)
设计一个电话目录有如下三个功能:
get
: Provide a number which is not assigned to anyone.check
: Check if a number is available or not.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题)的更多相关文章
- 【LeetCode】贪心 greedy(共38题)
[44]Wildcard Matching [45]Jump Game II (2018年11月28日,算法群衍生题) 题目背景和 55 一样的,问我能到达最后一个index的话,最少走几步. 题解: ...
- 【LeetCode】数学(共106题)
[2]Add Two Numbers (2018年12月23日,review) 链表的高精度加法. 题解:链表专题:https://www.cnblogs.com/zhangwanying/p/979 ...
- 【LeetCode】树(共94题)
[94]Binary Tree Inorder Traversal [95]Unique Binary Search Trees II (2018年11月14日,算法群) 给了一个 n,返回结点是 1 ...
- 【LeetCode】BFS(共43题)
[101]Symmetric Tree 判断一棵树是不是对称. 题解:直接递归判断了,感觉和bfs没有什么强联系,当然如果你一定要用queue改写的话,勉强也能算bfs. // 这个题目的重点是 比较 ...
- 【LeetCode】Recursion(共11题)
链接:https://leetcode.com/tag/recursion/ 247 Strobogrammatic Number II (2019年2月22日,谷歌tag) 给了一个 n,给出长度为 ...
- Leetcode 简略题解 - 共567题
Leetcode 简略题解 - 共567题 写在开头:我作为一个老实人,一向非常反感骗赞.收智商税两种行为.前几天看到不止两三位用户说自己辛苦写了干货,结果收藏数是点赞数的三倍有余,感觉自己的 ...
- LeetCode (85): Maximal Rectangle [含84题分析]
链接: https://leetcode.com/problems/maximal-rectangle/ [描述] Given a 2D binary matrix filled with '0's ...
- 剑指offer 面试38题
面试38题: 题:字符串的排列 题目:输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,ca ...
- Leetcode春季打卡活动 第二题:206. 反转链表
Leetcode春季打卡活动 第二题:206. 反转链表 206. 反转链表 Talk is cheap . Show me the code . /** * Definition for singl ...
随机推荐
- hdu 6047: Maximum Sequence (2017 多校第二场 1003)【贪心】
题目链接 可以贪心写,先把b数组按从小到大的顺序排个序,根据b[i]的值来产生a[n+i] 借助一个c数组,c[i]记录,j从i到n,a[j]-j的最大值,再加上一个实时更新的变量ma,记录从n+1到 ...
- shell学习记录----初识sed和gawk
Linux命令行与shell脚本编程大全中关于sed和gawk的介绍合在一起,而且结构有点乱. 不像之前的命令写的很清楚.所以这次我需要写下来整理一下. 一.sed部分 1.1 sed命令格式如下: ...
- [LOJ161] 仙人掌计数
Statement 带标号仙人掌计数问题. \(n< 131072\). Solution 设\(x\)个点的仙人掌个数的生成函数为\(C(x)\) 对于与根相邻的块, 还是仙人掌, 生成函数为 ...
- 李满春与WebGIS
李满春 ,男,1964年6月生,博士,教授,博导.现任南京大学科技处处长.地理信息科学系主任(兼).地理信息系统与遥感研究所所长(兼).国际地球系统科学研究所(学科特区)常务副所长(兼).第六届高等学 ...
- Largest Point
Largest Point Time Limit: 1500/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others)Tot ...
- (转)Kubernetes部署WordPress+MySQL
转:http://www.showerlee.com/archives/2336 这部分我们结合之前的k8s知识点给大家展示如何使用kubernetes部署wordpress+MySQL, 并利用NF ...
- What code you will get when you create a wcf library
创建wcf服务库的时候,系统自动生成的代码 // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”. [ServiceContract] publ ...
- PHP csv导出数据 (二)
全部导出和时间导出 html代码,全程并不需要引用什么插件 <include file="public@header"/> <link href="__ ...
- STM32 实现内部Flash的读写(HAL库版)
Flash 中文名字叫闪存,是一种长寿命的非易失性(断电数据不丢失)的存储器.可以对称为块的存储器单元块进行擦写和再编程,在进行写入操作之前必须先执行擦除.一个Nand Flash由多个块(Block ...
- vue全局自定义指令-元素拖拽
小白我用的是vue-cli的全家桶,在标签中加入v-drap则实现元素拖拽, 全局指令我是写在main.js中 Vue.directive('drag', { inserted: function ( ...