链接: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. springboot2整合logback.xml动态修改日志打印级别

    今天找bug烦到了,生产上的日志级别不能修改,非常不利于排查问题,于是想到了动态修改日志打印级别, 因为上一周把项目升级成springboot2,并且使用logback.xml管理日志打印,所以修改也 ...

  2. swift中为什么要创造出可选型?

    (1)因为nil这个东西,swift中没有就是没有.  Int? 叫 整型可选型,如果不提前声明,直接赋值变量 nil会报错 . 可以将Int赋值给Int?   ,但是不能将Int?赋值给Int . ...

  3. php实现进度条原理

    PHP实现进度条的原理: 模版替换,在页面设置一个标识,轮子自己的页面,不发请求给服务器,由服务器端获得进度,然后替换该页面标识,达到进度条效果. 页面代码: 1 2 3 4 5 6 7 8 9 10 ...

  4. 【LOMBOK】能引入 @Slf4j 注解,不能识别 log 的解决方法

    问题: 在pom.xml中加入引入了lombok的依赖,可以引用@Slf4j注解不能识别log 如:注:上面一篇博客,已经说明lombok的安装了,但是用的时候还有点问题. 1).把lombok.ja ...

  5. 【转】Django-template模板语言

    Django-template模板语言 转自:https://www.cnblogs.com/zzy-9318/p/8672945.html 一.常用语法 只需要记两种特殊符号: {{  }}和 {% ...

  6. SQL利用Case When Then Else End 多条件判断

    Select Case When a is not null then a When b is not null then b When c is not null then c When d is ...

  7. 牛客提高D3t1 破碎的矩阵

    分析 我们发现如果行的异或和等于列的异或和那么对于n-1行m-1列的所有数的选择都是任意的 因为一定可以在它的行末/列末选一个合适的数是的整体满足 但是我们发现对于右下角那一个数是否满足存疑 我们设矩 ...

  8. 实验1 C语言开发环境...

    #include<stdio.h> int main(){ int days; printf("输入一个整数:\n") ; scanf("%d",& ...

  9. 简单了解winform

    WinForm是·Net开发平台中对Windows Form的一种称谓. Windows窗体可用于设计窗体和可视控件,以创建丰富的基于Windows的窗体应用程序.可以访问数据库中的数据,并在窗体上显 ...

  10. jenkins之定时任务配置

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