(实际底层细节可能因编译器而异)
1. Sequence Containers:维持顺序的容器。
(a) vector:动态数组,用于O(1) 的随机读取。因为大部分算法的时间复杂度都会大于O(n),因此我们经常新建vector 来存储各种数据或中间变量。因为在尾部增删的复杂度是O(1) ,我们也可以把它当作stack 来用。
(b) list:双向链表,也可以当作stack 和queue 来使用。由于LeetCode 的题目多用Node 来表示链表,且链表不支持快速随机读取,因此我们很少用到这个数据结构。一个例外是经典的LRU 问题,我们需要利用链表的特性来解决。
(c) deque:双端队列,这是一个非常强大的数据结构,既支持O(1)随机读取,又支持O(1)时间的头部增删和尾部增删,不过有一定的额外开销。
(d) array:固定大小的数组,一般在刷题时我们不使用。
(e) forward_list:单向链表,一般在刷题时我们不使用。
2. Container Adaptors:基于其它容器实现的数据结构。
(a) stack:后入先出(LIFO)的数据结构,默认基于deque 实现(可改变)。stack 常用于深度优先搜索、一些字符串匹配问题以及单调栈问题。
(b) queue:先入先出(FIFO)的数据结构,默认基于deque 实现。queue 常用于广度优先搜索。
(c). priority_queue:最大值先出的数据结构,默认基于vector 实现堆结构。它可以在O(nlog(n))的时间排序数组,O(log(n))的时间插入任意值,O(1)的时间获得最大值,O(log(n))的时间删除最大值。priority_queue 常用于维护数据结构并快速获取最大或最小值。
3. Associative Containers:实现了排好序的数据结构。
(a) set:有序集合,元素不可重复,底层实现默认为红黑树,即一种特殊的二叉查找树(BST)。它可以在O(nlog(n))的时间排序数组,O(log(n))的时间插入、删除、查找任意值,O(log(n))的时间获得最小或最大值。这里注意,set 和priority_queue 都可以用于维护数据结构并快速获取最大最小值,但是它们的时间复杂度和功能略有区别,如priority_queue 默认不支持删除任意值,而set 获得最大或最小值的时间复杂度略高,具体使用哪个根据需求而定。
(b) multiset:支持重复元素的set。
(c) map:有序映射或有序表,在set 的基础上加上映射关系,可以对每个元素key 存一个值value。
(d) multimap:支持重复元素的map。
4. Unordered Associative Containers:对每个Associative Containers 实现了哈希版本。
(a) unordered_set:哈希集合,可以在O(1) 的时间快速插入、查找、删除元素,常用于快速的查询一个元素是否在这个容器内。
(b) unordered_multiset:支持重复元素的unordered_set。
(c) unordered_map:哈希映射或哈希表,在unordered_set 的基础上加上映射关系,可以对每一个元素key 存一个值value。在某些情况下,如果key 的范围已知且较小,我们也可以用vector 代替unordered_map,用位置表示key,用每个位置的值表示value。
(d) unordered_multimap:支持重复元素的unordered_map。
java 中几种常用数据结构_雨田上的行者的博客-CSDN博客_java 数据结构JAVA中常用的数据结构(java.util. 中)java中有几种常用的数据结构,主要分为Collection和map两个主要接口(接口只提供方法,并不提供实现),而程序中最终使用的数据结构是继承自这些接口的数据结构类。其主要的关系(继承关系)有: (----详细参见java api文档!)Collection---->Collectionshttps://blog.csdn.net/u010947402/article/details/51878166?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165165100316782246417950%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165165100316782246417950&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~baidu_landing_v2~default-1-51878166.142%5Ev9%5Econtrol,157%5Ev4%5Econtrol&utm_term=java+%E6%8F%90%E4%BE%9B%E7%9A%84%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84&spm=1018.2226.3001.4187图解 Java 中的数据结构及原理!_Java技术栈的博客-CSDN博客_java 数据结构原理作者:大道方圆cnblogs.com/xdecode/p/9321848.html最近在整理数据结构方面的知识, 系统化看了下Java中常用数据结构, 突发奇想用动画来绘制数据流转过程。主要基于jdk8, 可能会有些特性与jdk7之前不相同, 例如LinkedList LinkedHashMap中的双向列表不再是回环的。HashMap中的单链表是尾插, 而不是头插入等等, 后文不再赘叙这些差异, 本文目录结构如下:LinkedList经典的双链表结构, 适用于乱序插入, 删除. 指定序列操.https://blog.csdn.net/youanyyou/article/details/107930976?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165165107116781818773070%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165165107116781818773070&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_click~default-2-107930976.142%5Ev9%5Econtrol,157%5Ev4%5Econtrol&utm_term=java%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84&spm=1018.2226.3001.4187
LeetCode-448. Find All Numbers Disappeared in an Array [C++][Java]_贫道绝缘子的博客-CSDN博客Given an arraynumsofnintegers wherenums[i]is in the range[1, n], returnan array of all the integers in the range[1, n]that do not appear innums.https://blog.csdn.net/qq_15711195/article/details/124086603LeetCode-48. Rotate Image [C++][Java]_贫道绝缘子的博客-CSDN博客You are given ann x n2Dmatrixrepresenting an image, rotate the image by90degrees (clockwise). You have to rotate the imagein-place, which means you have to modify the input 2D matrix directly.DO NOTallocate another 2D matrix and do the rotationhttps://blog.csdn.net/qq_15711195/article/details/124086931LeetCode-240. Search a 2D Matrix II [C++][Java]_贫道绝缘子的博客-CSDN博客Write an efficient algorithm that searches for a valuetargetin anm x ninteger matrixmatrix.https://blog.csdn.net/qq_15711195/article/details/124086229LeetCode-769. Max Chunks To Make Sorted [C++][Java]_贫道绝缘子的博客-CSDN博客We splitarrinto some number ofchunks(i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Returnthe largest number of chunks we can make to sort the array.https://blog.csdn.net/qq_15711195/article/details/124259880LeetCode-768. Max Chunks To Make Sorted II [C++][Java]_贫道绝缘子的博客-CSDN博客We splitarrinto some number ofchunks(i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Returnthe largest number of chunks we can make to sort the array.https://blog.csdn.net/qq_15711195/article/details/124260130LeetCode-566. Reshape the Matrix [C++][Java]_贫道绝缘子的博客-CSDN博客In MATLAB, there is a handy function calledreshapewhich can reshape anm x nmatrix into a new one with a different sizer x ckeeping its original data.https://blog.csdn.net/qq_15711195/article/details/124472837
LeetCode-232. Implement Queue using Stacks [C++][Java]_贫道绝缘子的博客-CSDN博客Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push,peek,pop, andempty).https://blog.csdn.net/qq_15711195/article/details/124260419LeetCode-155. Min Stack [C++][Java]_贫道绝缘子的博客-CSDN博客Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.https://blog.csdn.net/qq_15711195/article/details/124261311LeetCode-20. Valid Parentheses [C++][Java]_贫道绝缘子的博客-CSDN博客Given a stringscontaining just the characters'(',')','{','}','['and']', determine if the input string is valid.https://blog.csdn.net/qq_15711195/article/details/124261952LeetCode-225. Implement Stack using Queues [C++][Java]_贫道绝缘子的博客-CSDN博客Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (push,top,pop, andempty).https://blog.csdn.net/qq_15711195/article/details/124473056
单调栈通过维持栈内值的单调递增(递减)性,在整体O(n)的时间内处理需要大小比较的
问题。
LeetCode-739. Daily Temperatures [C++][Java]_贫道绝缘子的博客-CSDN博客Given an array of integerstemperaturesrepresents the daily temperatures, returnan arrayanswersuch thatanswer[i]is the number of days you have to wait after theithday to get a warmer temperature. If there is no future day for which this is possiblehttps://blog.csdn.net/qq_15711195/article/details/124283447LeetCode-503. Next Greater Element II [C++][Java]_贫道绝缘子的博客-CSDN博客Given a circular integer arraynums(i.e., the next element ofnums[nums.length - 1]isnums[0]), returnthenext greater numberfor every element innums.https://blog.csdn.net/qq_15711195/article/details/124474462LeetCode-496. Next Greater Element I [C++][Java]_贫道绝缘子的博客-CSDN博客Thenext greater elementof some elementxin an array is thefirst greaterelement that isto the rightofxin the same array.https://blog.csdn.net/qq_15711195/article/details/124572976
优先队列(priority queue)可以在O(1) 时间内获得最大值,并且可以在O(log(n)) 时间内取出最大值或插入任意值。
优先队列常常用堆(heap)来实现。堆是一个完全二叉树,其每个节点的值总是大于等于子节点的值。实际实现堆时,我们通常用一个数组而不是用指针建立一个树。这是因为堆是完全二叉树,所以用数组表示时,位置i 的节点的父节点位置一定为i/2,而它的两个子节点的位置又一定分别为2i 和2i+1。
堆的实现方法中,最核心的两个操作是上浮和下沉:如果一个节点比父节点大,那
么需要交换这个两个节点;交换后还可能比它新的父节点大,因此需要不断地进行比较和交换操
作,我们称之为上浮;类似地,如果一个节点比父节小,也需要不断地向下进行比较和交换操作,
我们称之为下沉。如果一个节点有两个子节点,我们总是交换最大的子节点。
vector heap;
// 获得最大值
void top() {
return heap[0];
}
// 插入任意值:把新的数字放在最后一位,然后上浮
void push(int k) {
heap.push_back(k);
swim(heap.size() - 1);
}
// 删除最大值:把最后一个数字挪到开头,然后下沉
void pop() {
heap[0] = heap.back();
heap.pop_back();
sink(0);
}
// 上浮
void swim(int pos) {
while (pos > 1 && heap[pos/2] < heap[pos])) {
swap(heap[pos/2], heap[pos]);
pos /= 2;
}
}
// 下沉
void sink(int pos) {
while (2 * pos <= N) {
int i = 2 * pos;
if (i < N && heap[i] < heap[i+1]) ++i;
if (heap[pos] >= heap[i]) break;
swap(heap[pos], heap[i]);
pos = i;
}
}
通过将算法中的大于号和小于号互换,我们也可以得到一个快速获得最小值的优先队列。
LeetCode-23. Merge k Sorted Lists [C++][Java]_贫道绝缘子的博客-CSDN博客You are given an array ofklinked-listslists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.https://blog.csdn.net/qq_15711195/article/details/124283795LeetCode-218. The Skyline Problem [C++][Java]_贫道绝缘子的博客-CSDN博客A city'sskylineis the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, returntheskylineformed by these buildings collectively.https://blog.csdn.net/qq_15711195/article/details/124285381LeetCode-870. Advantage Shuffle [C++][Java]_贫道绝缘子的博客-CSDN博客You are given two integer arraysnums1andnums2both of the same length. Theadvantageofnums1with respect tonums2is the number of indicesifor whichnums1[i] > nums2[i].https://blog.csdn.net/qq_15711195/article/details/124570694
LeetCode-239. Sliding Window Maximum [C++][Java]_贫道绝缘子的博客-CSDN博客There is a sliding window of sizekwhich is moving from the very left of the array to the very right. You can only see theknumbers in the window. Each time the sliding window moves right by one position. Returnthe max sliding window.https://blog.csdn.net/qq_15711195/article/details/124308391
哈希表,又称散列表,使用O(n) 空间复杂度存储数据,通过哈希函数映射位置,从而实现近似O(1)时间复杂度的插入、查找、删除等操作。
C++ 中的哈希集合为unordered_set,可以查找元素是否在集合中。如果需要同时存储键和值,则需要用unordered_map,可以用来统计频率,记录内容等等。如果元素有穷,并且范围不大,那么可以用一个固定大小的数组来存储或统计元素。例如我们需要统计一个字符串中所有字母的出现次数,则可以用一个长度为26 的数组来进行统计,其哈希函数即为字母在字母表的位置,这样空间复杂度就可以降低为常数。
template
class HashTable {
private:
vector> hash_table;
// 哈希函数
int myhash(const T & obj) const {
return hash(obj, hash_table.size());
}
public:
// size最好是质数
HashTable(int size=31) {
hash_table.reserve(size);
hash_table.resize(size);
}
~HashTable() {}
// 查找哈希表是否存在该值
bool contains(const T & obj) {
int hash_value = myhash(obj);
const list & slot = hash_table[hash_value];
std::list::const_iterator it = slot.cbegin();
for (; it != slot.cend() && *it != obj; ++it);
return it != slot.cend();
}
// 插入值
bool insert(const T & obj) {
if (contains(obj))
return false;
}
int hash_value = myhash(obj);
std::list & slot = hash_table[hash_value];
slot.push_front(obj);
return true;
}
// 删除值
bool remove(const T & obj) {
list & slot = hash_table[myhash(obj)];
auto it = find(slot.begin(), slot.end(), obj);
if (it == slot.end()) {
return false;
}
slot.erase(it);
return true;
}
};
// 一个简单的对整数实现的哈希函数
int hash(const int & key, const int &tableSize) {
return key % tableSize;
}
如果需要大小关系的维持,且插入查找并不过于频繁,则可以使用有序的set/map 来代替
unordered_set/unordered_map。
LeetCode-1. Two Sum [C++]_贫道绝缘子的博客-CSDN博客Given an array of integers, returnindicesof the two numbers such that they add up to a specific target.https://blog.csdn.net/qq_15711195/article/details/122143418LeetCode-15. 3Sum [C++]_贫道绝缘子的博客-CSDN博客Given an arraynumsofnintegers, are there elementsa,b,cinnumssuch thata+b+c= 0? Find all unique triplets in the array which gives the sum of zero.https://blog.csdn.net/qq_15711195/article/details/122143546LeetCode-18. 4Sum [C++]_贫道绝缘子的博客-CSDN博客Given an arraynumsofnintegers and an integertarget, are there elementsa,b,c, anddinnumssuch thata+b+c+d=target? Find all unique quadruplets in the array which gives the sum oftarget.https://blog.csdn.net/qq_15711195/article/details/122143625LeetCode-128. Longest Consecutive Sequence [C++][Java]_贫道绝缘子的博客-CSDN博客Given an unsorted array of integersnums, returnthe length of the longest consecutive elements sequence. You must write an algorithm that runs inO(n)time.https://blog.csdn.net/qq_15711195/article/details/124309513LeetCode-149. Max Points on a Line [C++][Java]_贫道绝缘子的博客-CSDN博客Given an array ofpointswherepoints[i] = [xi, yi]represents a point on theX-Yplane, returnthe maximum number of points that lie on the same straight line.https://blog.csdn.net/qq_15711195/article/details/124399544LeetCode-217. Contains Duplicate [C++][Java]_贫道绝缘子的博客-CSDN博客Given an integer arraynums, returntrueif any value appearsat least twicein the array, and returnfalseif every element is distinct.https://blog.csdn.net/qq_15711195/article/details/124483135LeetCode-594. Longest Harmonious Subsequence [C++][Java]_贫道绝缘子的博客-CSDN博客We define a harmonious array as an array where the difference between its maximum value and its minimum value isexactly1. Given an integer arraynums, returnthe length of its longest harmonious subsequence among all its possible subsequences.https://blog.csdn.net/qq_15711195/article/details/124484293LeetCode-870. Advantage Shuffle [C++][Java]_贫道绝缘子的博客-CSDN博客You are given two integer arraysnums1andnums2both of the same length. Theadvantageofnums1with respect tonums2is the number of indicesifor whichnums1[i] > nums2[i].https://blog.csdn.net/qq_15711195/article/details/124570694
LeetCode-332. Reconstruct Itinerary [C++][Java]_贫道绝缘子的博客-CSDN博客All of the tickets belong to a man who departs from"JFK", thus, the itinerary must begin with"JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.https://blog.csdn.net/qq_15711195/article/details/124453422LeetCode-697. Degree of an Array [C++][Java]_贫道绝缘子的博客-CSDN博客Given a non-empty array of non-negative integersnums, thedegreeof this array is defined as the maximum frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous) subarray ofnums, that has the same degreehttps://blog.csdn.net/qq_15711195/article/details/124483810
一维的前缀和,二维的积分图,都是把每个位置之前的一维线段或二维矩形预先存储,方便加速计算。如果需要对前缀和或积分图的值做寻址,则要存在哈希表里;如果要对每个位置记录前缀和或积分图的值,则可以储存到一维或二维数组里,也常常伴随着动态规划。
LeetCode-303. Range Sum Query - Immutable [C++][Java]_贫道绝缘子的博客-CSDN博客Calculate thesumof the elements ofnumsbetween indicesleftandrightinclusivewhereleft <= right.https://blog.csdn.net/qq_15711195/article/details/124461184LeetCode-304. Range Sum Query 2D - Immutable [C++][Java]_贫道绝缘子的博客-CSDN博客Calculate thesumof the elements ofmatrixinside the rectangle defined by itsupper left corner(row1, col1)andlower right corner(row2, col2).https://blog.csdn.net/qq_15711195/article/details/124461507LeetCode-560. Subarray Sum Equals K [C++][Java]_贫道绝缘子的博客-CSDN博客Given an array of integersnumsand an integerk, returnthe total number of subarrays whose sum equals tok.https://blog.csdn.net/qq_15711195/article/details/124462091LeetCode-313. Super Ugly Number [C++][Java]_贫道绝缘子的博客-CSDN博客Asuper ugly numberis a positive integer whose prime factors are in the arrayprimes. Given an integernand an array of integersprimes, returnthenthsuper ugly number. Thenthsuper ugly numberisguaranteedto fit in a32-bitsigned integer.https://blog.csdn.net/qq_15711195/article/details/124484928LeetCode-307. Range Sum Query - Mutable [C++][Java]_贫道绝缘子的博客-CSDN博客Given an integer arraynums, handle multiple queries of the following types: Updatethe value of an element innums. Calculate thesumof the elements ofnumsbetween indicesleftandrightinclusivewhereleft <= right.https://blog.csdn.net/qq_15711195/article/details/124571706
LeetCode-146. LRU Cache [C++][Java]_贫道绝缘子的博客-CSDN博客Design a data structure that follows the constraints of aLeast Recently Used (LRU) cache.https://blog.csdn.net/qq_15711195/article/details/126456263?spm=1001.2014.3001.5502LeetCode-380. Insert Delete GetRandom O(1) [C++][Java]_贫道绝缘子的博客-CSDN博客You must implement the functions of the class such that each function works inaverageO(1)time complexity.https://blog.csdn.net/qq_15711195/article/details/126456464?spm=1001.2014.3001.5502LeetCode-432. All O`one Data Structure [C++][Java]_贫道绝缘子的博客-CSDN博客Design a data structure to store the strings' count with the ability to return the strings with minimum and maximum counts.https://blog.csdn.net/qq_15711195/article/details/126458620?spm=1001.2014.3001.5502LeetCode 716. 最大栈(双栈 / list+map)_Michael阿明的博客-CSDN博客文章目录1. 题目2. 解题2.1 双栈解法2.2 list+map1. 题目设计一个最大栈,支持 push、pop、top、peekMax 和 popMax 操作。push(x) -- 将元素 x 压入栈中。pop() -- 移除栈顶元素并返回这个值。top() -- 返回栈顶元素。peekMax() -- 返回栈中最大元素。popMax() -- 返回栈中最大的元素,并将其删除。如果有多个最大元素,只要删除最靠近栈顶的那个。 样例 1:MaxStack stack = newhttps://blog.csdn.net/qq_21201267/article/details/107102162?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522166112653716781790765119%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=166112653716781790765119&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~sobaiduend~default-1-107102162-null-null.142^v42^control,185^v2^control&utm_term=LeetCode%20716&spm=1018.2226.3001.4187