链接: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. libopencv_imgcodecs3.so.3.3.1: undefined reference to `TIFFReadDirectory@LIBTIFF_4.0

    ubundu 编译 C++工程时遇到的: 解决方案: https://blog.csdn.net/qq_29572513/article/details/88742652

  2. Xib中用自动布局设置UIScrollView的ContenSize

    1. 在UIScrollView上拖一个UIView 2.设置UIScrollView上下左右约束为0,设置UIView上下左右约束为0,并且设置水平中线约束.那么可以把水平中线约束拖到对应视图,利用 ...

  3. php7新特性的理解和比较

    1. null合并运算符(??) ??语法: 如果变量存在且值不为NULL,它就会返回自身的值,否则返回它的第二个操作数. //php7以前 if判断 if(empty($_GET['param']) ...

  4. 新建 SecondPresenter 实现类

    package com.test.mvp.mvpdemo.mvp.v6.presenter; import com.test.mvp.mvpdemo.mvp.v6.SecondContract;imp ...

  5. django缓存优化(一)

    在配置之前,先介绍一个实用的工具: 当我们进入虚拟环境,在shell中进行操作的时候,往往要导入django的各种配置文件: from django.x import xxxx 这时我们可以借助dja ...

  6. 用PHP实现一些常见的排序算法

    1.冒泡排序: 两两相比,每循环一轮就不用再比较最后一个元素了,因为最后一个元素已经是最大或者最小. function maopaoSort ($list) { $len = count($list) ...

  7. linux 复制到远程服务器

    scp 文件路径 root@192.168.0.1:文件夹路径 会提示你输入远程服务器密码

  8. 像计算机科学家一样思考python-第2章 变量、表达式和语句

    感想: 1.程序出现语义错误时,画状态图是一个很好的调试办法.打印出关键变量在不同代码处理后值的变化,就能发现问题的蛛丝马迹. 2.每当学习新语言特性时,都应当在交互模式中进行尝试,并故意犯下错误,看 ...

  9. html基础与表格的理解·

    1.静态网页与动态网页的区别:是否访问数据库 2.超文本:超文本是指超出文本的范围,可以插入声音视频,表格图片等 3.标记语言与网页结构:标记语言就是标签,网页结构包含<html>< ...

  10. Vagrant 手册之网络 - 端口转发

    原文地址 Vagrantfile 配置文件中端口转发的网络标识符:forwarded_port,例如: config.vm.network "forwarded_port", gu ...