文章目录
-
- [1. 两数之和](#1. 两数之和)
- [2. 字母异位词分组](#2. 字母异位词分组)
- [3. 最长连续序列](#3. 最长连续序列)
- [4. 移动零](#4. 移动零)
- [5. 盛最多水的容器](#5. 盛最多水的容器)
- [6. 三数之和](#6. 三数之和)
- [7. 接雨水](#7. 接雨水)
- [8. 无重复字符的最长子串](#8. 无重复字符的最长子串)
- [9. 找到字符串中所有字母异位词](#9. 找到字符串中所有字母异位词)
- [10. 和为 K 的子数组](#10. 和为 K 的子数组)
- [11. 滑动窗口最大值](#11. 滑动窗口最大值)
- [12. 最小覆盖子串](#12. 最小覆盖子串)
- [13. 最大子数组和](#13. 最大子数组和)
- [14. 合并区间](#14. 合并区间)
- [15. 轮转数组](#15. 轮转数组)
- [16. 除了自身以外数组的乘积](#16. 除了自身以外数组的乘积)
- [17. 缺失的第一个正数](#17. 缺失的第一个正数)
- [18. 矩阵置零](#18. 矩阵置零)
- [19. 螺旋矩阵](#19. 螺旋矩阵)
- [20. 旋转图像](#20. 旋转图像)
- [21. 搜索二维矩阵 II](#21. 搜索二维矩阵 II)
- [22. 相交链表](#22. 相交链表)
- [23. 反转链表](#23. 反转链表)
- [24. 回文链表](#24. 回文链表)
- [25. 环形链表](#25. 环形链表)
- [26. 环形链表 II](#26. 环形链表 II)
- [27. 合并两个有序链表](#27. 合并两个有序链表)
- [28. 两数相加](#28. 两数相加)
- [29. 删除链表的倒数第 N 个结点](#29. 删除链表的倒数第 N 个结点)
- [30. 两两交换链表中的节点](#30. 两两交换链表中的节点)
- [31. K 个一组翻转链表](#31. K 个一组翻转链表)
- [32. 随机链表的复制](#32. 随机链表的复制)
- [33. 排序链表](#33. 排序链表)
- [34. 合并 K 个升序链表](#34. 合并 K 个升序链表)
- [35. LRU 缓存](#35. LRU 缓存)
- [36. 二叉树的中序遍历](#36. 二叉树的中序遍历)
- [37. 二叉树的最大深度](#37. 二叉树的最大深度)
- [38. 翻转二叉树](#38. 翻转二叉树)
- [39. 对称二叉树](#39. 对称二叉树)
- [40. 二叉树的直径](#40. 二叉树的直径)
- [41. 二叉树的层序遍历](#41. 二叉树的层序遍历)
- [42. 将有序数组转换为二叉搜索树](#42. 将有序数组转换为二叉搜索树)
- [43. 验证二叉搜索树](#43. 验证二叉搜索树)
- [44. 二叉搜索树中第 K 小的元素](#44. 二叉搜索树中第 K 小的元素)
- [45. 二叉树的右视图](#45. 二叉树的右视图)
- [46. 二叉树展开为链表](#46. 二叉树展开为链表)
- [47. 从前序与中序遍历序列构造二叉树](#47. 从前序与中序遍历序列构造二叉树)
- [48. 路径总和 III](#48. 路径总和 III)
- [49. 二叉树的最近公共祖先](#49. 二叉树的最近公共祖先)
- [50. 二叉树中的最大路径和](#50. 二叉树中的最大路径和)
- [51. 岛屿数量](#51. 岛屿数量)
- [52. 腐烂的橘子](#52. 腐烂的橘子)
- [53. 课程表](#53. 课程表)
- [54. 实现 Trie (前缀树)](#54. 实现 Trie (前缀树))
- [55. 全排列](#55. 全排列)
- [56. 子集](#56. 子集)
- [57. 电话号码的字母组合](#57. 电话号码的字母组合)
- [58. 组合总和](#58. 组合总和)
- [59. 括号生成](#59. 括号生成)
- [60. 单词搜索](#60. 单词搜索)
- [61. 分割回文串](#61. 分割回文串)
- [62. N 皇后](#62. N 皇后)
- [63. 搜索插入位置](#63. 搜索插入位置)
- [64. 搜索二维矩阵](#64. 搜索二维矩阵)
- [65. 在排序数组中查找元素的第一个和最后一个位置](#65. 在排序数组中查找元素的第一个和最后一个位置)
- [66. 搜索旋转排序数组](#66. 搜索旋转排序数组)
- [67. 寻找旋转排序数组中的最小值](#67. 寻找旋转排序数组中的最小值)
- [68. 寻找两个正序数组的中位数](#68. 寻找两个正序数组的中位数)
- [69. 有效的括号](#69. 有效的括号)
- [70. 最小栈](#70. 最小栈)
- [71. 字符串解码](#71. 字符串解码)
- [72. 每日温度](#72. 每日温度)
- [73. 柱状图中最大的矩形](#73. 柱状图中最大的矩形)
- [74. 数组中的第K个最大元素](#74. 数组中的第K个最大元素)
- [75. 前 K 个高频元素](#75. 前 K 个高频元素)
- [76. 数据流的中位数](#76. 数据流的中位数)
- [77. 买卖股票的最佳时机](#77. 买卖股票的最佳时机)
- [78. 跳跃游戏](#78. 跳跃游戏)
- [79. 跳跃游戏 II](#79. 跳跃游戏 II)
- [80. 划分字母区间](#80. 划分字母区间)
- [81. 爬楼梯](#81. 爬楼梯)
- [82. 杨辉三角](#82. 杨辉三角)
- [83. 打家劫舍](#83. 打家劫舍)
- [84. 完全平方数](#84. 完全平方数)
- [85. 零钱兑换](#85. 零钱兑换)
- [86. 单词拆分](#86. 单词拆分)
- [87. 最长递增子序列](#87. 最长递增子序列)
- [88. 乘积最大子数组](#88. 乘积最大子数组)
- [89. 分割等和子集](#89. 分割等和子集)
- [90. 最长有效括号](#90. 最长有效括号)
- [91. 不同路径](#91. 不同路径)
- [92. 最小路径和](#92. 最小路径和)
- [93. 最长回文子串](#93. 最长回文子串)
- [94. 最长公共子序列](#94. 最长公共子序列)
- [95. 编辑距离](#95. 编辑距离)
- [96. 只出现一次的数字](#96. 只出现一次的数字)
- [97. 多数元素](#97. 多数元素)
- [98. 颜色分类](#98. 颜色分类)
- [99. 下一个排列](#99. 下一个排列)
- [100. 寻找重复数](#100. 寻找重复数)
本文记录刷 leetcode hot 100 的代码。
1. 两数之和
cpp
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> index;
for(int i = 0; i < nums.size(); i++)
{
index[nums[i]] = i;
}
for(int i = 0; i < nums.size(); i++)
{
int x = target - nums[i];
if(index.count(x) && index[x] != i)
{
return {index[x], i};
}
}
return {};
}
};
2. 字母异位词分组
cpp
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string, vector<string>> hashtable;
for(auto& str : strs)
{
string s = str;
sort(str.begin(), str.end());
hashtable[str].push_back(s);
}
vector<vector<string>> result;
for(auto it = hashtable.begin(); it != hashtable.end(); it++)
{
result.push_back(it->second);
}
return result;
}
};
3. 最长连续序列
cpp
class Solution {
public:
int longestConsecutive(vector<int>& nums)
{
unordered_set<int> us;
for(auto& e : nums)
{
us.insert(e);
}
int ret = 0;
for(auto& e : us)
{
if(us.count(e - 1)) continue; // 优化, 不然要 O(n*n)
int i = 1;
for(; us.count(e + i); i++);
ret = max(i, ret);
}
return ret;
}
};
4. 移动零
cpp
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int pre = -1;
for(int i = 0; i < nums.size(); i++)
{
if(nums[i]) swap(nums[i], nums[++pre]);
}
}
};
5. 盛最多水的容器
计算更新之后只移动矮的那一边,因为移动高的的话矮的那边没变,高最还是矮的那边,但是宽变小了,面积必然变小。如果移动矮的那边还有可能使得高更高。
cpp
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0, right = height.size() - 1;
int result = 0;
while(left < right)
{
result = max(result, (right - left) * min(height[left], height[right]));
if(height[left] < height[right])
{
left++;
}
else
{
right--;
}
}
return result;
}
};
6. 三数之和
如果用哈希表的话很难去重,特别麻烦。这里采用排序 + 双指针。
先固定一个数 x,从 x 之后的子数组中找另外两个数,用双指针 left 和 right,起始时分别在子数组的两端,如果加起来大了,那么 right--,如果小了,那么 left++。
并且排序过后可以进行几个剪枝操作。
cpp
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums)
{
sort(nums.begin(), nums.end());
vector<vector<int>> ret;
for(int i = 0; i < nums.size() - 2; i++)
{
if(i > 0 && nums[i] == nums[i - 1]) continue; // 去重
if(nums[i] > 0) break; // 剪枝
int target = -1 * nums[i];
int left = i + 1, right = nums.size() - 1;
while(left < right)
{
if(nums[left] > target) break; // 剪枝
if(nums[left] + nums[right] < target) left++;
else if(nums[left] + nums[right] > target) right--;
else
{
ret.push_back({nums[i], nums[left], nums[right]});
int x = nums[left], y = nums[right];
while(left < right && nums[left] == x) left++; // 去重
while(right > left && nums[right] == y) right--; // 去重
}
}
}
return ret;
}
};
7. 接雨水
cpp
class Solution
{
public:
int trap(vector<int>& height)
{
int size = height.size();
vector<int> preMax(size, 0);
vector<int> sufMax(size, 0);
for(int i = 1; i < size; i++) preMax[i] = max(height[i - 1], preMax[i - 1]);
for(int i = size - 2; i >= 0; i--) sufMax[i] = max(sufMax[i + 1], height[i + 1]);
int result = 0;
for(int i = 0; i < size; i++)
{
result += max(min(preMax[i], sufMax[i]) - height[i], 0);
}
return result;
}
};
8. 无重复字符的最长子串
cpp
class Solution
{
public:
int lengthOfLongestSubstring(string s)
{
if(s.empty()) return 0;
int left = 0, right = 0;
int ret = 0;
unordered_map<char, int> hashtable;
while(right < s.size())
{
hashtable[s[right]]++;
while(hashtable[s[right]] > 1)
{
hashtable[s[left]]--;
left++;
}
ret = max(ret, right - left + 1);
right++;
}
return ret;
}
};
9. 找到字符串中所有字母异位词
cpp
class Solution {
public:
vector<int> findAnagrams(string s, string p)
{
array<int, 26> standard, arr;
for(auto& e : p) standard[e - 'a']++;
int left = 0, right = 0;
vector<int> ret;
while(right < s.size())
{
arr[s[right] - 'a']++;
if(right - left > p.size() - 1)
{
arr[s[left] - 'a']--;
left++;
}
if(arr == standard) ret.push_back(left);
right++;
}
return ret;
}
};
10. 和为 K 的子数组
cpp
class Solution {
public:
int subarraySum(vector<int>& nums, int k)
{
unordered_map<int, int> hashtable;
int ret = 0, presum = 0;
for(int i = 0; i < nums.size(); ++i)
{
// 在计算 i 位置之前, 哈希表只保存 [0, i - 1] 位置的前缀和
hashtable[presum]++;
presum += nums[i];
if(hashtable.count(presum - k)) ret += hashtable[presum - k];
}
return ret;
}
};
11. 滑动窗口最大值
单调队列
cpp
class Solution
{
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k)
{
vector<int> ret;
deque<int> dq;
for(int i = 0; i < nums.size(); i++)
{
// 维护一个从头到尾单调递减的队列
// 如果来的数比较大, 那么靠近队尾那些小的数都出队列
while(dq.size() && nums[dq.back()] <= nums[i]) dq.pop_back();
dq.push_back(i);
// 如果不在窗口了, 也移除队列
if(dq.back() - dq.front() + 1 > k) dq.pop_front();
if(i + 1 >= k) ret.push_back(nums[dq.front()]);
}
return ret;
}
};
12. 最小覆盖子串
cpp
class Solution
{
public:
string minWindow(string s, string t)
{
int target[52] = {0}, arr[52] = {0};
int left = 0, right = 0;
int retLeft = -1, retRight = 1e5 + 10;
int count = 0, kind = 0;
string ret;
for(auto& e : t)
{
if('a' <= e && e <= 'z') target[e - 'a']++;
else target[e - 'A' + 26]++;
}
for(int i = 0; i < 52; i++)
{
if(target[i]) kind++;
}
while(right < s.size())
{
int idx;
if('a' <= s[right] && s[right] <= 'z') idx = s[right] - 'a';
else idx = s[right] - 'A' + 26;
arr[idx]++;
if(arr[idx] == target[idx]) count++;
while(count == kind && left <= right)
{
if((right - left + 1) < (retRight - retLeft + 1))
{
retLeft = left;
retRight = right;
}
if('a' <= s[left] && s[left] <= 'z') idx = s[left] - 'a';
else idx = s[left] - 'A' + 26;
left++;
arr[idx]--;
if(arr[idx] < target[idx]) count--;
}
right++;
}
return retLeft == -1 ? "" : s.substr(retLeft, retRight - retLeft + 1);
}
};
13. 最大子数组和
贪心
cpp
class Solution {
public:
int maxSubArray(vector<int>& nums)
{
int result = INT_MIN;
int sum = 0;
for(int i = 0; i < nums.size(); i++)
{
sum += nums[i];
result = max(result, sum);
if(sum < 0) sum = 0;
}
return result;
}
};
分治
cpp
class Solution {
public:
int _maxSubArray(vector<int>& nums, int left, int right)
{
if(left >= right) return nums[left];
int mid = left + (right - left) / 2;
int x = _maxSubArray(nums, left, mid);
int y = _maxSubArray(nums, mid + 1, right);
int left_sum = 0, right_sum = 0, left_max = INT_MIN, right_max = INT_MIN;
for(int i = mid; i >= left; i--)
{
left_sum += nums[i];
left_max = max(left_max, left_sum);
}
for(int i = mid + 1; i <= right; i++)
{
right_sum += nums[i];
right_max = max(right_max, right_sum);
}
int z = left_max + right_max;
return max(max(x, y), z);
}
int maxSubArray(vector<int>& nums)
{
int left = 0, right = nums.size() - 1;
return _maxSubArray(nums, left, right);
}
};
14. 合并区间
cpp
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals)
{
sort(intervals.begin(), intervals.end(), [](const vector<int>& x, const vector<int>& y){
return x[0] < y[0];
});
int res_left = intervals[0][0], res_right = intervals[0][1];
int cur_left, cur_right;
vector<vector<int>> ret;
for(size_t i = 1; i < intervals.size(); i++)
{
cur_left = intervals[i][0], cur_right = intervals[i][1];
if(cur_left > res_right)
{
ret.push_back({res_left, res_right});
res_left = cur_left;
res_right = cur_right;
}
else
{
res_right = max(res_right, cur_right);
}
}
ret.push_back({res_left, res_right});
return ret;
}
};
15. 轮转数组
这题方法比较多,参考官方题解
c
void reverse(int* nums, int left, int right){
while(left < right){
int tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
++left;
--right;
}
}
// C
void rotate(int* nums, int numsSize, int k) {
if(k>=numsSize) k%=numsSize;
reverse(nums, 0, numsSize-k-1);
reverse(nums, numsSize-k, numsSize-1);
reverse(nums, 0, numsSize-1);
}
cpp
class Solution {
public:
void rotate(vector<int>& nums, int k)
{
int n = nums.size();
k %= n;
int count = gcd(n, k); // 环的数量
for(int start = 0; start < count; start++)
{
int pre = nums[start];
int cur = start;
do
{
int next = (cur + k) % n;
swap(pre, nums[next]);
cur = next;
} while(cur != start);
}
}
};
16. 除了自身以外数组的乘积
cpp
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums)
{
int n = nums.size();
vector<int> pre(n, 1);
vector<int> suf(n, 1);
for(int i = 1; i < n; i++)
pre[i] = pre[i - 1] * nums[i - 1];
for(int i = n - 2; i >= 0; i--)
suf[i] = suf[i + 1] * nums[i + 1];
vector<int> ret(n, 0);
for(int i = 0; i < n; i++)
ret[i] = pre[i] * suf[i];
return ret;
}
};
cpp
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums)
{
// 不使用额外空间
int n = nums.size();
vector<int> suf_to_ret(n, 1);
for(int i = n - 2; i >= 0; i--)
{
suf_to_ret[i] = suf_to_ret[i + 1] * nums[i + 1];
}
int pre = nums[0];
for(int i = 1; i < n; i++)
{
suf_to_ret[i] = suf_to_ret[i] * pre;
pre *= nums[i];
}
return suf_to_ret;
}
};
17. 缺失的第一个正数
cpp
class Solution {
public:
int firstMissingPositive(vector<int>& nums)
{
int n = nums.size();
for(int i = 0; i < n; i++)
{
while(nums[i] < n && nums[i] >= 0 && nums[i] != i && nums[i] != nums[nums[i]]) swap(nums[i], nums[nums[i]]);
}
int ret = 0;
for(int i = 1; i < n; i++)
{
if(nums[i] != i)
{
ret = i;
break;
}
}
if(ret == 0 && nums[0] == n) return n + 1;
if(ret == 0) return n;
return ret;
}
};
18. 矩阵置零
cpp
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix)
{
int r = matrix.size(), c = matrix[0].size();
bool first_row = false, first_col = false;
for(int i = 0; i < r; i++)
{
if(matrix[i][0] == 0)
{
first_col = true;
break;
}
}
for(int j = 0; j < c; j++)
{
if(matrix[0][j] == 0)
{
first_row = true;
break;
}
}
for(int i = 1; i < r; i++)
for(int j = 1; j < c; j++)
if(matrix[i][j] == 0) matrix[0][j] = matrix[i][0] = 0;
for(int i = 1; i < r; i++)
if(matrix[i][0] == 0)
for(int j = 0; j < c; j++) matrix[i][j] = 0;
for(int j = 1; j < c; j++)
if(matrix[0][j] == 0)
for(int i = 0; i < r; i++) matrix[i][j] = 0;
if(first_row) for(int j = 0; j < c; j++) matrix[0][j] = 0;
if(first_col) for(int i = 0; i < r; i++) matrix[i][0] = 0;
}
};
19. 螺旋矩阵
cpp
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix)
{
pair<int, int> directions[4] =
{
{0, 1},
{1, 0},
{-1, 0},
{0, -1}
};
vector<int> ret;
int r = matrix.size(), c = matrix[0].size();
int count = r * c;
int idx = 0, x = 0, y = -1;
while(1)
{
int nx = x + directions[idx].first;
int ny = y + directions[idx].second;
if(nx >= 0 && nx < r && ny >= 0 && ny < c && matrix[nx][ny] != -101)
{
ret.push_back(matrix[nx][ny]);
if(ret.size() == count) break;
matrix[nx][ny] = -101;
x = nx, y = ny;
}
else idx = (idx + 1) % 4;
}
return ret;
}
};
20. 旋转图像
转置 + 对称
cpp
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int r = matrix.size(), c = matrix[0].size();
for(int i = 0; i < r; i++)
for(int j = i + 1; j < c; j++)
swap(matrix[i][j], matrix[j][i]);
for(int i = 0; i < r; i++)
for(int j = 0; j < c / 2; j++)
swap(matrix[i][j], matrix[i][c - j - 1]);
}
};
21. 搜索二维矩阵 II
排除法
cpp
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
int r = matrix.size(), c = matrix[0].size();
int x = 0, y = c - 1;
while(matrix[x][y] != target)
{
while(x < r && y >= 0 && matrix[x][y] > target) y--;
while(x < r && y >= 0 && matrix[x][y] < target) x++;
if(x >= r || y < 0) return false;
if(matrix[x][y] == target) return true;
}
return true;
}
};
22. 相交链表
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
ListNode* pa = headA, *pb = headB;
int lenA = 0, lenB = 0;
for(; pa; pa = pa->next) lenA++;
for(; pb; pb = pb->next) lenB++;
pa = headA, pb = headB;
int k = 0;
if(lenA > lenB)
{
k = lenA - lenB;
for(int i = 0; i < k; i++) pa = pa->next;
}
else
{
k = lenB - lenA;
for(int i = 0; i < k; i++) pb = pb->next;
}
while(pa != pb)
{
pa = pa->next;
pb = pb->next;
}
return pa;
}
};
23. 反转链表
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode* reverseList(ListNode* head)
{
if(head == nullptr || head->next == nullptr) return head;
ListNode* newNode = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newNode;
}
};
24. 回文链表
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
ListNode* pre = nullptr, *cur = head;
while(cur != nullptr)
{
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
bool isPalindrome(ListNode* head)
{
int len = 0;
ListNode* pNode = head;
for(; pNode; pNode = pNode->next, len++);
ListNode* mid = head;
for(int i = 0; i < len / 2; mid = mid->next, i++);
ListNode* left = head;
ListNode* right = reverseList(mid);
for(int i = 0; i < len / 2; i++)
{
if(left->val != right->val) return false;
left = left->next;
right = right->next;
}
return true;
}
};
25. 环形链表
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
bool hasCycle(ListNode *head)
{
ListNode* fast = head, *slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow) return true;
}
return false;
}
};
26. 环形链表 II
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode* fast = head, *slow = head;
ListNode* pa = head, *pb = nullptr;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
pb = fast;
break;
}
}
if(!pb) return nullptr;
while(pa != pb)
{
pa = pa->next;
pb = pb->next;
}
return pa;
}
};
27. 合并两个有序链表
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2)
{
ListNode dummy;
ListNode* pre = &dummy;
ListNode* p1 = list1, *p2 = list2;
while(p1 && p2)
{
if(p1->val < p2->val)
{
pre->next = p1;
pre = p1;
p1 = p1->next;
}
else
{
pre->next = p2;
pre = p2;
p2 = p2->next;
}
}
pre->next = p1 == nullptr ? p2 : p1;
return dummy.next;
}
};
28. 两数相加
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* p1 = l1, *p2 = l2;
int leak = 0;
ListNode* firstNode = new ListNode(-1);
ListNode* pre = firstNode;
while(p1 || p2 || leak)
{
int tmp = leak;
if(p1) tmp += p1->val, p1 = p1->next;
if(p2) tmp += p2->val, p2 = p2->next;
int curVal = tmp % 10;
leak = tmp / 10;
ListNode* curNode = new ListNode(curVal);
pre->next = curNode;
pre = pre->next;
}
return firstNode->next;
}
};
29. 删除链表的倒数第 N 个结点
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode dummy(-1, head);
ListNode* fast = head, *slow = head, *pre = &dummy;
for(int i = 0; i < n; i++) fast = fast->next;
while(fast)
{
pre = slow;
fast = fast->next;
slow = slow->next;
}
pre->next = slow->next;
return dummy.next;
}
};
30. 两两交换链表中的节点
可以直接复用K 个一组翻转链表。
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head)
{
int k = 2;
ListNode* p = head;
int len = 0;
for(; p; p = p->next, len++);
ListNode dummy(-1, head);
ListNode* preTail = &dummy;
int round = len / k;
ListNode* pre = nullptr;
ListNode* cur = preTail->next;
while(round--)
{
ListNode* tail = cur;
for(int i = 0; i < k; i++)
{
ListNode* nextNode = cur->next;
cur->next = pre;
pre = cur;
cur = nextNode;
}
tail->next = cur;
preTail->next = pre;
preTail = tail;
}
return dummy.next;
}
};
也可以递归:
c
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head)
{
if(head == NULL || head->next == NULL) return head;
struct ListNode* newhead = swapPairs(head->next->next);
struct ListNode* ret = head->next;
head->next->next = head;
head->next = newhead;
return ret;
}
31. K 个一组翻转链表
cpp
class Solution
{
public:
ListNode* reverseKGroup(ListNode* head, int k)
{
ListNode* p = head;
int len = 0;
for(; p; p = p->next, len++);
ListNode dummy(-1, head);
ListNode* preTail = &dummy; // 上一组的尾节点
int round = len / k;
ListNode* pre = nullptr;
ListNode* cur = preTail->next;
while(round--)
{
// 当前组的(反转后的)尾节点
ListNode* tail = cur;
// 反转当前组
for(int i = 0; i < k; i++)
{
ListNode* nextNode = cur->next;
cur->next = pre;
pre = cur;
cur = nextNode;
}
// 反转后 cur 变成下一组的(未反转的)头
// 当前组的尾节点需要指向这个头
// 如果下一组不需要反转, 这个逻辑是对的
// 如果下一组需要反转, 等到反转之后, 在下一组的逻辑中会把当前组的尾节点指向反转后的头的
tail->next = cur;
// 反转后 pre 尾当前组的头
// 上一组的尾节点指向当前组的头
preTail->next = pre;
// 更新尾节点信息
preTail = tail;
}
return dummy.next;
}
};
32. 随机链表的复制
注意指针的变化
cpp
/*
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
*/
class Solution {
public:
Node* copyRandomList(Node* head)
{
for(Node* p = head; p; p = p->next->next)
{
Node* newNode = new Node(p->val);
newNode->next = p->next;
p->next = newNode;
}
int count = 0;
for(Node* p = head; p; p = p->next, count++)
{
if(count % 2) continue;
if(p->random) p->next->random = p->random->next;
else p->next->random = nullptr;
}
Node dummy(0);
dummy.next = head;
Node* pre = &dummy;
Node* p = head;
while(p)
{
Node* nextNode = p->next->next;
pre->next = p->next;
pre = p->next;
p->next = nextNode;
p = nextNode;
}
return dummy.next;
}
};
33. 排序链表
递归版:
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
// 返回中间节点(有两个时返回左边的)
ListNode* getMidNode(ListNode* left, ListNode* right)
{
int len = 0;
for(ListNode* p = left; p != right; p = p->next) len++;
len++;
int step = (len - 1) / 2;
ListNode* midNode = left;
while(step--) midNode = midNode->next;
return midNode;
}
// 合并两个有序链表
ListNode* merge(ListNode* p1, ListNode* p2)
{
if(!p1) return p2;
if(!p2) return p1;
ListNode* list1 = p1, *list2 = p2;
ListNode* pre = nullptr;
while(p1 && p2)
{
if(p1->val < p2->val)
{
if(pre) pre->next = p1;
pre = p1;
p1 = p1->next;
}
else
{
if(pre) pre->next = p2;
pre = p2;
p2 = p2->next;
}
}
if(p1) pre->next = p1;
if(p2) pre->next = p2;
return list1->val < list2->val ? list1 : list2;
}
ListNode* _sortList(ListNode* left, ListNode* right)
{
if(left == right) return left;
ListNode* midNode = getMidNode(left, right);
ListNode* midNext = midNode->next;
midNode->next = nullptr;
ListNode* p1 = _sortList(left, midNode);
ListNode* p2 = _sortList(midNext, right);
return merge(p1, p2);
}
public:
ListNode* sortList(ListNode* head)
{
if(!head) return head;
ListNode* right = head;
while(right->next) right = right->next;
return _sortList(head, right);
}
};
迭代版:
具体算法:
- 遍历链表,获取链表长度 length
- 初始化步长 step=1
- 循环直到 step ≥ length
- 每轮循环,从链表头节点开始
- 分割出两段长为 step 的链表,合并,把合并后的链表插到新链表的末尾。重复该步骤,直到链表遍历完毕。
- 把 step 扩大一倍。回到第 4 步
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
int getListLen(ListNode* head)
{
int len = 0;
for(ListNode* p = head; p; p = p->next) len++;
return len;
}
// 合并两个有序链表, 返回合并后的头尾节点
pair<ListNode*, ListNode*> merge(ListNode* list1, ListNode* list2)
{
ListNode* p1 = list1;
ListNode* p2 = list2;
ListNode dummy;
ListNode* pre = &dummy;
while(p1 && p2)
{
if(p1->val < p2->val)
{
pre->next = p1;
pre = p1;
p1 = p1->next;
}
else
{
pre->next = p2;
pre = p2;
p2 = p2->next;
}
}
ListNode* retTail = nullptr;
if(p1)
{
pre->next = p1;
retTail = p1;
}
if(p2)
{
pre->next = p2;
retTail = p2;
}
while(retTail && retTail->next) retTail = retTail->next;
ListNode* retHead = dummy.next;
return {retHead, retTail};
}
// 从 head 开始分割长为 len 的链表, 返回分割链表的原下一个节点
ListNode* splitList(ListNode* head, int len)
{
ListNode* cur = head;
while(cur && --len) cur = cur->next;
if(cur == nullptr || cur->next == nullptr) return nullptr;
ListNode* nextNode = cur->next;
cur->next = nullptr;
return nextNode;
}
public:
ListNode* sortList(ListNode* head)
{
ListNode dummy(0, head);
ListNode* cur = head;
ListNode* preMergedTail = &dummy; // 上一次合并之后的链表的尾节点
int listLen = getListLen(head);
for(int mergeLength = 1; mergeLength < listLen; mergeLength *= 2)
{
cur = dummy.next;
preMergedTail = &dummy;
while(cur)
{
ListNode* leftHead = cur;
ListNode* rightHead = splitList(leftHead, mergeLength);
cur = splitList(rightHead, mergeLength);
auto [mergedHead, mergedTail] = merge(leftHead, rightHead);
preMergedTail->next = mergedHead;
preMergedTail = mergedTail;
}
}
return dummy.next;
}
};
34. 合并 K 个升序链表
可以全部连起来再链表排序(复用 33. 排序链表)的代码。
还可以按顺序两两合并,但是这样很多节点都会重复参与合并的的运算。一个巧妙的思路是,把 lists 一分为二(尽量均分),先合并前一半的链表,再合并后一半的链表,然后把这两个链表合并成最终的链表。如何合并前一半的链表呢?我们可以继续一分为二。如此分下去直到只有一个链表,此时无需合并。
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2)
{
ListNode dummy;
ListNode* pre = &dummy;
ListNode* p1 = list1, *p2 = list2;
while(p1 && p2)
{
if(p1->val < p2->val)
{
pre->next = p1;
pre = p1;
p1 = p1->next;
}
else
{
pre->next = p2;
pre = p2;
p2 = p2->next;
}
}
pre->next = p1 == nullptr ? p2 : p1;
return dummy.next;
}
ListNode* _mergeKLists(vector<ListNode*>& lists, int left, int right)
{
if(left == right) return lists[left];
int n = right - left + 1;
int mid = left + (n - 1) / 2;
ListNode* leftHead = _mergeKLists(lists, left, mid);
ListNode* rightHead = _mergeKLists(lists, mid + 1, right);
return mergeTwoLists(leftHead, rightHead);
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
if(lists.empty()) return nullptr;
int size = lists.size();
return _mergeKLists(lists, 0, size - 1);
}
};
迭代:

cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2)
{
ListNode dummy;
ListNode* pre = &dummy;
ListNode* p1 = list1, *p2 = list2;
while(p1 && p2)
{
if(p1->val < p2->val)
{
pre->next = p1;
pre = p1;
p1 = p1->next;
}
else
{
pre->next = p2;
pre = p2;
p2 = p2->next;
}
}
pre->next = p1 == nullptr ? p2 : p1;
return dummy.next;
}
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
int n = lists.size();
if(n <= 1) return lists.empty() ? nullptr : lists[0];
for(int step = 1; step < n; step *= 2)
{
for(int i = 0; i < n - step; i += step * 2)
{
// 合并结果要写回数组
lists[i] = mergeTwoLists(lists[i], lists[i + step]);
}
}
return lists[0];
}
};
35. LRU 缓存
cpp
class LRUCache
{
public:
LRUCache(int capacity) : _capacity(capacity) {}
int get(int key)
{
auto it = listMap.find(key);
if (it == listMap.end()) return -1;
// splice 接口(下面为 3 个重载的其中一个):
// 把 other 中的单个节点 it 移动到 pos 之前
// void splice(const_iterator pos, list& other, const_iterator it);
// 直接把节点 splice 到头部,不销毁不新建
cacheList.splice(cacheList.begin(), cacheList, it->second);
return it->second->second;
}
void put(int key, int value)
{
auto it = listMap.find(key);
if (it != listMap.end())
{
// key 已存在:更新 value,移到头部
it->second->second = value;
cacheList.splice(cacheList.begin(), cacheList, it->second);
return;
}
// key 不存在:容量满则淘汰
if (cacheList.size() >= _capacity)
{
int oldKey = cacheList.back().first;
listMap.erase(oldKey);
cacheList.pop_back(); // 现在只需弹尾部
}
// 插入新节点到头部
cacheList.emplace_front(key, value);
listMap[key] = cacheList.begin();
}
private:
int _capacity;
list<pair<int, int>> cacheList; // list 里面保存 {key, value} 就不用单独开一个哈希表存 {key, value}
unordered_map<int, list<pair<int,int>>::iterator> listMap;
};
36. 二叉树的中序遍历
递归版本:
cpp
class Solution {
vector<int> ret;
void _inorderTraversal(TreeNode* root)
{
if(root == nullptr) return;
_inorderTraversal(root->left);
ret.push_back(root->val);
_inorderTraversal(root->right);
}
public:
vector<int> inorderTraversal(TreeNode* root)
{
_inorderTraversal(root);
return ret;
}
};
非递归,用栈模拟递归:
cpp
class Solution
{
public:
vector<int> inorderTraversal(TreeNode* root)
{
stack<TreeNode*> st;
vector<int> ret;
TreeNode* cur = root;
while(cur || !st.empty())
{
while(cur)
{
st.push(cur);
cur = cur->left;
}
TreeNode* node = st.top();
ret.push_back(node->val);
st.pop();
cur = node->right;
}
return ret;
}
};
非递归不用栈(Morris 遍历,线索二叉树):
cpp
class Solution
{
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> ret;
TreeNode* pre = nullptr; // 记录前驱节点
TreeNode* cur = root;
while(cur)
{
// cur 有左孩子
if(cur->left)
{
// pre 找到前驱节点, 线索化
// 注意此时有可能是已经线索化返回后的 cur
pre = cur->left;
while(pre->right && pre->right != cur) pre = pre->right;
// 如果此时是第一遍访问, 还没有线索化, 那么就线索化并且接着往左重复该逻辑
if(pre->right == nullptr)
{
pre->right = cur;
cur = cur->left;
continue;
}
// 到了这里说明左子树已经访问完毕了, 需要去掉线索
pre->right = nullptr;
}
// cur 没有左孩子, 记录当前节点并沿着线索返回
ret.push_back(cur->val);
cur = cur->right;
}
return ret;
}
};
37. 二叉树的最大深度
cpp
class Solution {
public:
int maxDepth(TreeNode* root) {
return root == nullptr ? 0 : max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
38. 翻转二叉树
cpp
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(root == nullptr) return root;
TreeNode* invertLeft = invertTree(root->left);
TreeNode* invertRight = invertTree(root->right);
swap(root->left, root->right);
return root;
}
};
39. 对称二叉树
递归:
cpp
class Solution
{
bool _isSymmetric(TreeNode* root1, TreeNode* root2)
{
if(!root1 && !root2) return true;
if(root1 && !root2) return false;
if(root2 && !root1) return false;
if(root1->val != root2->val) return false;
return _isSymmetric(root1->left, root2->right) && _isSymmetric(root1->right, root2->left);
}
public:
bool isSymmetric(TreeNode* root)
{
return _isSymmetric(root->left, root->right);
}
};
迭代:用队列,每次取两个节点,相邻两个节点的值应该是相等的。
cpp
class Solution
{
public:
bool check(TreeNode *u, TreeNode *v)
{
queue <TreeNode*> q;
q.push(u); q.push(v);
while (!q.empty()) {
u = q.front(); q.pop();
v = q.front(); q.pop();
if (!u && !v) continue;
if ((!u || !v) || (u->val != v->val)) return false;
q.push(u->left);
q.push(v->right);
q.push(u->right);
q.push(v->left);
}
return true;
}
bool isSymmetric(TreeNode* root) {
return check(root, root);
}
};
40. 二叉树的直径
cpp
// dfs 计算从传入的 root 节点开始到叶子节点的最大路径长(称为链)
// 一个直径起始就是一棵二叉树所有节点的最大(左链 + 右链拼成的路径)的最大值
class Solution
{
int ret = 0;
int dfs(TreeNode* root)
{
if(root == nullptr) return 0;
int leftMax = dfs(root->left);
int rightMax = dfs(root->right);
ret = max(ret, leftMax + rightMax);
return max(leftMax, rightMax) + 1;
}
public:
int diameterOfBinaryTree(TreeNode* root)
{
dfs(root);
return ret;
}
};
41. 二叉树的层序遍历
cpp
class Solution
{
public:
vector<vector<int>> levelOrder(TreeNode* root)
{
if(!root) return {};
queue<TreeNode*> q; q.push(root);
vector<vector<int>> ret;
while(!q.empty())
{
int count = q.size();
vector<int> t;
for(int i = 0; i < count; i++)
{
TreeNode* node = q.front(); q.pop();
t.push_back(node->val);
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
ret.push_back(t);
}
return ret;
}
};
42. 将有序数组转换为二叉搜索树
cpp
class Solution
{
TreeNode* _sortedArrayToBST(vector<int>& nums, int left, int right)
{
if(left > right) return nullptr;
int mid = left + (right - left) / 2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = _sortedArrayToBST(nums, left, mid - 1);
root->right = _sortedArrayToBST(nums, mid + 1, right);
return root;
}
public:
TreeNode* sortedArrayToBST(vector<int>& nums)
{
return _sortedArrayToBST(nums, 0, nums.size() - 1);
}
};
43. 验证二叉搜索树
递归中序遍历:
cpp
class Solution
{
long long pre = LLONG_MIN;
public:
bool isValidBST(TreeNode* root)
{
if(root == nullptr) return true;
if(!isValidBST(root->left)) return false;
if(root->val <= pre) return false;
pre = root->val;
return isValidBST(root->right);
}
};
Morris 遍历 + 验证:
cpp
class Solution
{
public:
bool isValidBST(TreeNode* root)
{
TreeNode* cur = root;
TreeNode* pre = nullptr;
TreeNode* preNode = nullptr;
bool ret = true;
while(cur)
{
if(cur->left)
{
pre = cur->left;
while(pre->right && pre->right != cur) pre = pre->right;
if(pre->right == nullptr)
{
pre->right = cur;
cur = cur->left;
continue;
}
pre->right = nullptr;
}
if(preNode && preNode->val >= cur->val) ret = false;
preNode = cur;
cur = cur->right;
}
return ret;
}
};
前序遍历:
cpp
bool isValidBST(TreeNode* root, long long left = LLONG_MIN, long long right = LLONG_MAX)
{
if (root == nullptr) return true;
long long x = root->val;
return left < x && x < right &&
isValidBST(root->left, left, x) &&
isValidBST(root->right, x, right);
}
return 后面的三个条件可以交换顺序,但是会影响性能。
44. 二叉搜索树中第 K 小的元素
cpp
class Solution
{
int ret = 0;
int count = 0;
void _kthSmallest(TreeNode* root)
{
if(root == nullptr) return;
_kthSmallest(root->left);
--count;
if(count == 0) ret = root->val;
_kthSmallest(root->right);
}
public:
int kthSmallest(TreeNode* root, int k)
{
count = k;
_kthSmallest(root);
return ret;
}
};
如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?
AVL 树
45. 二叉树的右视图
BFS:
cpp
class Solution
{
public:
vector<int> rightSideView(TreeNode* root)
{
if(!root) return {};
vector<int> ret;
queue<TreeNode*> q; q.push(root);
while(!q.empty())
{
int n = q.size();
int num = 0;
for(int i = 0; i < n; i++)
{
TreeNode* node = q.front(); q.pop();
num = node->val;
if(node->left) q.push(node->left);
if(node->right) q.push(node->right);
}
ret.push_back(num);
}
return ret;
}
};
DFS:右子树优先
cpp
class Solution
{
public:
vector<int> ans;
void dfs(TreeNode* root, int depth)
{
if (!root) return;
// 如果当前节点所在的这一层,还没有记录过节点,就记录当前节点。
if (depth == ans.size())
{
ans.push_back(root->val);
}
dfs(root->right, depth + 1);
dfs(root->left, depth + 1);
}
vector<int> rightSideView(TreeNode* root)
{
dfs(root, 0);
return ans;
}
};
46. 二叉树展开为链表
头插法:
cpp
class Solution
{
TreeNode* head = nullptr;
public:
void flatten(TreeNode* root)
{
if(root == nullptr) return;
flatten(root->right);
flatten(root->left);
root->right = head;
root->left = nullptr;
head = root;
}
};
分治:如果左子树和右子树都转化成链表了,之后如何做
cpp
class Solution
{
TreeNode* dfs(TreeNode* root)
{
if(root == nullptr) return nullptr;
TreeNode* leftTail = dfs(root->left);
TreeNode* rightTail = dfs(root->right);
// 左子树不为空才进行下面的链接操作, 如果为空就相当于已经链接完成了
if(leftTail)
{
// 注意顺序
leftTail->right = root->right;
root->right = root->left;
root->left = nullptr;
}
// 优先返回右子树的尾部, 其次左子树的尾部, 都为空则返回 root
return rightTail ? rightTail : (leftTail ? leftTail : root);
}
public:
void flatten(TreeNode* root)
{
(void)dfs(root);
}
};
47. 从前序与中序遍历序列构造二叉树
分治法,用了哈希表优化查节点位置的效率。这里我用的是数组下标表示一段数组,没有拷贝。
cpp
class Solution
{
unordered_map<int, int> index;
TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int preLeft, int preRight, int inLeft, int inRight)
{
if(preLeft > preRight) return nullptr;
TreeNode* root = new TreeNode(preorder[preLeft]);
int i = index[preorder[preLeft]];
int leftTreeInRight = i - 1;
int rightTreeInLeft = i + 1;
int leftTreeCount = leftTreeInRight - inLeft + 1;
int leftTreePreRight = preLeft + leftTreeCount;
int rightTreePreLeft = leftTreePreRight + 1;
preLeft++;
root->left = _buildTree(preorder, inorder, preLeft, leftTreePreRight, inLeft, leftTreeInRight);
root->right = _buildTree(preorder, inorder, rightTreePreLeft, preRight, rightTreeInLeft, inRight);
return root;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
for(int i = 0; i < inorder.size(); i++) index[inorder[i]] = i;
return _buildTree(preorder, inorder, 0, preorder.size() - 1, 0, inorder.size() - 1);
}
};
48. 路径总和 III
记录从根节点到遍历节点之前的前缀和,类似于和为 K 的子数组
cpp
class Solution
{
// 假设根节点值为 8, 目标和也为 8, 不初始化 {0, 1} 就无法统计这个单节点路径
// 可以认为根节点有一个虚拟的 0 节点
unordered_map<long long, int> cnt = {{0, 1}};
int ret;
long long preSum;
void dfs(TreeNode* root, int targetSum)
{
if(!root) return;
preSum += root->val;
// 注意先查询, 再更新哈希表
if(cnt.count(preSum - targetSum)) ret += cnt[preSum - targetSum];
cnt[preSum]++;
dfs(root->left, targetSum);
dfs(root->right, targetSum);
// 回溯
cnt[preSum]--;
preSum -= root->val;
}
public:
int pathSum(TreeNode* root, int targetSum)
{
dfs(root, targetSum);
return ret;
}
};
49. 二叉树的最近公共祖先
cpp
class Solution
{
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
{
if(!root) return nullptr;
if(root == p || root == q) return root;
// 去左右子树找 LCA, 如果子树只有一个目标节点, 返回这个目标节点, 如果没有, 返回空
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
// 如果都找到了, 说明当前节点就是 LCA
if(left && right) return root;
// 如果只有一边找到了, 说明 p, q 的 LCA 结果就在那一边
return left ? left : right;
}
};
50. 二叉树中的最大路径和
cpp
class Solution
{
// 类似树形 dp 的思想
// 1. 一般是后续遍历
// 2. 左子树提供什么信息, 右子树提供什么信息
// 3. 如何根据左右子树的信息, 整合当前子树的信息
// 4. 要向上返回什么信息
int ret = INT_MIN;
int dfs(TreeNode* root)
{
if(root == nullptr) return 0;
int leftMax = dfs(root->left);
int rightMax = dfs(root->right);
// 如果为负贡献, 就没有必要拼接
ret = max(ret, root->val + max(leftMax, 0) + max(rightMax, 0));
// 如果左右子树都是负的, 那么根节点就没必要接收负贡献
return max(max(leftMax, rightMax), 0) + root->val;
}
public:
int maxPathSum(TreeNode* root)
{
dfs(root);
return ret;
}
};
51. 岛屿数量
cpp
class Solution
{
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
public:
int numIslands(vector<vector<char>>& grid)
{
int r = grid.size();
int c = grid[0].size();
queue<pair<int, int>> q;
int cnt = 0;
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
if(grid[i][j] == '0') continue;
cnt++;
q.emplace(i, j);
while(q.size())
{
auto [x, y] = q.front(); q.pop();
for(int i = 0; i < 4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < r && ny >= 0 && ny < c && grid[nx][ny] == '1')
{
q.emplace(nx, ny);
grid[nx][ny] = '0';
}
}
}
}
}
return cnt;
}
};
52. 腐烂的橘子
cpp
class Solution
{
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
public:
// 多源 BFS
int orangesRotting(vector<vector<int>>& grid)
{
int r = grid.size();
int c = grid[0].size();
queue<pair<int, int>> q;
int time = 0, fresh = 0;
for(int i = 0; i < r; i++)
for(int j = 0; j < c; j++)
{
if(grid[i][j] == 2) q.emplace(i, j);
else if(grid[i][j] == 1) fresh++;
}
// 当最后一轮腐烂完, 如果没有新鲜橘子了就退出, 否则会空转一轮
while(!q.empty() && fresh > 0)
{
int sz = q.size();
for(int i = 0; i < sz; i++)
{
auto [x, y] = q.front(); q.pop();
for(int k = 0; k < 4; k++)
{
int nx = x + dx[k];
int ny = y + dy[k];
if(nx >= 0 && nx < r && ny >= 0 && ny < c && grid[nx][ny] == 1)
{
q.emplace(nx, ny);
grid[nx][ny] = 2;
fresh--;
}
}
}
time++;
}
return fresh > 0 ? -1 : time;
}
};
53. 课程表
cpp
class Solution
{
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites)
{
vector<vector<int>> edges(numCourses); // 建图
vector<int> in(numCourses, 0); // 统计入度
for(auto& p : prerequisites)
{
int p1 = p[0], p2 = p[1];
// p2 --> p1
edges[p2].push_back(p1);
in[p1]++;
}
queue<int> q;
int count = 0;
for(int i = 0; i < in.size(); i++)
if(in[i] == 0) q.push(i);
while(q.size())
{
int index = q.front(); q.pop();
for(auto& p : edges[index])
{
in[p]--;
if(in[p] == 0) q.push(p);
}
count++;
}
return count == numCourses;
}
};
54. 实现 Trie (前缀树)
cpp
class Trie
{
public:
Trie() = default;
void insert(string word)
{
int cur = 0;
p[cur]++;
for(auto& ch : word)
{
int path = ch - 'a';
if(tree[cur][path] == 0) tree[cur][path] = ++idx;
cur = tree[cur][path];
p[cur]++;
}
e[cur]++;
}
bool search(string word)
{
int cur = 0;
for(auto& ch : word)
{
int path = ch - 'a';
if(tree[cur][path] == 0) return false;
cur = tree[cur][path];
}
return e[cur] > 0;
}
bool startsWith(string prefix)
{
int cur = 0;
for(auto& ch : prefix)
{
int path = ch - 'a';
if(tree[cur][path] == 0) return false;
cur = tree[cur][path];
}
return p[cur] > 0;
}
private:
int tree[40010][26];
int e[40010];
int p[40010];
int idx;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/
55. 全排列
cpp
class Solution
{
vector<int> path;
vector<vector<int>> ret;
bool vis[21];
void dfs(vector<int>& nums)
{
if(path.size() == nums.size())
{
ret.push_back(path);
return;
}
for(auto& num : nums)
{
if(vis[num + 10]) continue;
path.push_back(num);
vis[num + 10] = true;
dfs(nums);
path.pop_back();
vis[num + 10] = false;
}
}
public:
vector<vector<int>> permute(vector<int>& nums)
{
dfs(nums);
return ret;
}
};
56. 子集
cpp
class Solution
{
vector<vector<int>> ret{{}};
vector<int> path;
void dfs(vector<int>& nums, int index)
{
if(index == nums.size()) return;
for(int i = index; i < nums.size(); i++)
{
path.push_back(nums[i]);
ret.push_back(path);
dfs(nums, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> subsets(vector<int>& nums)
{
dfs(nums, 0);
return ret;
}
};
57. 电话号码的字母组合
画决策树即可
cpp
class Solution
{
const string map[10] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
vector<string> ret;
string path;
void dfs(string& digits, int index)
{
if(path.size() == digits.size())
{
ret.push_back(path);
return;
}
const string& s = map[digits[index] - '0'];
for(int i = 0; i < s.size(); i++)
{
path.push_back(s[i]);
dfs(digits, index + 1);
path.pop_back();
}
}
public:
vector<string> letterCombinations(string digits)
{
dfs(digits, 0);
return ret;
}
};
58. 组合总和
cpp
class Solution
{
vector<vector<int>> ret;
pair<vector<int>, int> path;
void dfs(vector<int>& candidates, int target, int index)
{
if(path.second >= target)
{
if(path.second == target) ret.push_back(path.first);
return;
}
for(int i = index; i < candidates.size(); i++)
{
path.first.push_back(candidates[i]);
path.second += candidates[i];
dfs(candidates, target, i);
path.first.pop_back();
path.second -= candidates[i];
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
dfs(candidates, target, 0);
return ret;
}
};
优化:排序 + 剪枝。不递归进去判断超出 target 时的情况,而是在循环里判断然后 break。另外可以把 pair 拆开
cpp
class Solution
{
vector<vector<int>> ret;
vector<int> path;
int curSum = 0;
void dfs(vector<int>& candidates, int target, int index)
{
if(curSum == target)
{
if(curSum == target) ret.push_back(path);
return;
}
for(int i = index; i < candidates.size(); i++)
{
if(curSum + candidates[i] > target) break; // 剪枝, 不递归进去判断
path.push_back(candidates[i]);
curSum += candidates[i];
dfs(candidates, target, i);
path.pop_back();
curSum -= candidates[i];
}
}
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target)
{
sort(candidates.begin(), candidates.end()); // 排序, 这样后面才能那样剪枝
dfs(candidates, target, 0);
return ret;
}
};
59. 括号生成
cpp
class Solution
{
string path;
vector<string> ret;
void dfs(int n, int leftParCount, int rightParCount)
{
if(path.size() == n * 2)
{
ret.push_back(path);
return;
}
// 左括号
if(leftParCount < n)
{
path.push_back('(');
dfs(n, leftParCount + 1, rightParCount);
path.pop_back();
}
// 右括号
if(rightParCount < leftParCount)
{
path.push_back(')');
dfs(n, leftParCount, rightParCount + 1);
path.pop_back();
}
}
public:
vector<string> generateParenthesis(int n)
{
path.reserve(2 * n);
dfs(n, 0, 0);
return ret;
}
};
60. 单词搜索
没必要记录 string path,用 pos 就可以判断结没结束,注意要记录每个格子访问过没有。
cpp
class Solution
{
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
bool ret = false;
vector<vector<bool>> vis;
void dfs(vector<vector<char>>& board, string& word, int x, int y, int pos)
{
if(pos == (int)word.size() - 1)
{
ret = true;
return;
}
int r = board.size();
int c = board[0].size();
for(int i = 0; i < 4; i++)
{
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && nx < r && ny >= 0 && ny < c && !vis[nx][ny] && board[nx][ny] == word[pos + 1])
{
vis[nx][ny] = true;
dfs(board, word, nx, ny, pos + 1);
vis[nx][ny] = false;
}
}
}
public:
bool exist(vector<vector<char>>& board, string word)
{
int r = board.size();
int c = board[0].size();
vis.assign(r, vector<bool>(c, false));
for(int i = 0; i < r; i++)
{
for(int j = 0; j < c; j++)
{
if(board[i][j] == word[0])
{
vis[i][j] = true;
dfs(board, word, i, j, 0);
vis[i][j] = false;
}
}
}
return ret;
}
};
61. 分割回文串
cpp
class Solution
{
vector<vector<bool>> dp;
vector<vector<string>> ret;
vector<string> path;
void dfs(const string& s, int pos)
{
if(pos == s.size())
{
ret.push_back(path);
return;
}
for(int i = pos; i < s.size(); i++)
{
if(!dp[pos][i]) continue;
path.push_back(s.substr(pos, i - pos + 1));
dfs(s, i + 1); // 注意是 i + 1 而不是 pos + 1
path.pop_back();
}
}
public:
vector<vector<string>> partition(string s)
{
int n = s.size();
path.reserve(n);
dp.assign(n, vector<bool>(n, false));
// 预处理回文串
for(int i = n - 1; i >= 0; i--)
for(int j = i; j < n; j++)
if(s[i] == s[j]) dp[i][j] = i + 1 >= j ? true : dp[i + 1][j - 1];
dfs(s, 0);
return ret;
}
};
62. N 皇后
cpp
class Solution
{
vector<vector<string>> ret;
vector<string> path;
vector<bool> col;
vector<bool> zdj;
vector<bool> fdj;
void dfs(int n, int r)
{
if(r == n)
{
ret.push_back(path);
return;
}
for(int j = 0; j < n; j++)
{
if(col[j] || zdj[r + j] || fdj[j - r + n - 1])
{
continue;
}
col[j] = true;
zdj[r + j] = true;
fdj[j - r + n - 1] = true;
path[r][j] = 'Q';
dfs(n, r + 1);
col[j] = false;
zdj[r + j] = false;
fdj[j - r + n - 1] = false;
path[r][j] = '.';
}
}
public:
vector<vector<string>> solveNQueens(int n)
{
path.assign(n, string(n, '.'));
col.assign(n, false);
zdj.assign(2 * n, false);
fdj.assign(2 * n, false);
dfs(n, 0);
return ret;
}
};
63. 搜索插入位置
由于元素不重复,两种写法都行。
如果有 target,找的就是 target 的下标。如果没有,那么找的是小于 target 的最大的(如果有小于的,没有的话就是数组开头元素)。
cpp
class Solution
{
public:
int searchInsert(vector<int>& nums, int target)
{
int left = 0, right = nums.size() - 1;
while(left < right)
{
int mid = left + (right - left) / 2;
if(nums[mid] >= target) right = mid;
else left = mid + 1;
}
return nums[left] >= target ? left : left + 1;
}
};
cpp
class Solution
{
public:
int searchInsert(vector<int>& nums, int target)
{
int left = 0, right = nums.size() - 1;
while(left < right)
{
int mid = left + (right - left + 1) / 2;
if(nums[mid] >= target) right = mid - 1;
else left = mid;
}
return nums[left] >= target ? left : left + 1;
}
};
64. 搜索二维矩阵
cpp
class Solution
{
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
int r = matrix.size();
int c = matrix[0].size();
int left = 0, right = r - 1;
while(left < right)
{
int mid = left + (right - left + 1) / 2;
if(matrix[mid][0] > target) right = mid - 1;
else left = mid;
}
if(matrix[left][0] == target) return true;
int curr = left;
left = 0, right = c - 1;
while(left < right)
{
int mid = left + (right - left + 1) / 2;
if(matrix[curr][mid] > target) right = mid - 1;
else left = mid;
}
if(matrix[curr][left] == target) return true;
return false;
}
};
拉成一维:
cpp
class Solution
{
public:
bool searchMatrix(vector<vector<int>>& matrix, int target)
{
int r = matrix.size();
int c = matrix[0].size();
int left = 0, right = r * c - 1;
while(left < right)
{
int mid = left + (right - left + 1) / 2;
if(matrix[mid / c][mid % c] > target) right = mid - 1;
else left = mid;
}
if(matrix[left / c][left % c] == target) return true;
return false;
}
};
65. 在排序数组中查找元素的第一个和最后一个位置
cpp
class Solution
{
public:
vector<int> searchRange(vector<int>& nums, int target)
{
if(nums.empty()) return {-1, -1};
int first = -1, last = -1;
int left = 0, right = nums.size() - 1;
while(left < right)
{
int mid = left + (right - left) / 2;
if(nums[mid] < target) left = mid + 1;
else right = mid;
}
if(nums[left] != target) return {-1, -1};
first = left;
left = 0, right = nums.size() - 1;
while(left < right)
{
int mid = left + (right - left + 1) / 2;
if(nums[mid] <= target) left = mid;
else right = mid - 1;
}
if(nums[left] != target) return {-1, -1};
last = left;
return {first, last};
}
};
66. 搜索旋转排序数组
cpp
class Solution
{
int find(const vector<int>& nums, int target,
int left, int right)
{
// if(left > right) return -1;
while(left < right)
{
int mid = left + (right - left) / 2;
if(nums[mid] < target) left = mid + 1;
else right = mid;
}
return nums[left] == target ? left : -1;
}
public:
int search(vector<int>& nums, int target)
{
int n = nums.size();
int left = 0, right = n - 1;
// 找到最小元素的下标
while(left < right)
{
int mid = left + (right - left) / 2;
if(nums[mid] > nums[right]) left = mid + 1;
else right = mid;
}
int pivot = left;
if(target <= nums[n - 1]) return find(nums, target, pivot, n - 1);
return find(nums, target, 0, pivot - 1);
}
};
67. 寻找旋转排序数组中的最小值
cpp
class Solution
{
public:
int findMin(vector<int>& nums)
{
int n = nums.size();
int left = 0, right = n - 1;
while(left < right)
{
int mid = left + (right - left) / 2;
if(nums[mid] > nums[right]) left = mid + 1;
else right = mid;
}
return nums[left];
}
};
68. 寻找两个正序数组的中位数
cpp
class Solution
{
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2)
{
int n1 = nums1.size(), n2 = nums2.size();
if(n1 > n2) return findMedianSortedArrays(nums2, nums1);
int left = 0, right = n1;
// 二分划分位置
// 如果写 while(left < right), 那么退出循环时 left == right, 而这种情况还没有检验
while(left <= right)
{
int mid = left + (right - left) / 2;
// i 和 j 分别表示分割后的 nums1 和 nums2 的左半部分元素个数
int i = mid, j = (n1 + n2 + 1) / 2 - i;
int left1 = i == 0 ? INT_MIN : nums1[i - 1];
int left2 = j == 0 ? INT_MIN : nums2[j - 1];
int right1 = i == n1 ? INT_MAX : nums1[i];
int right2 = j == n2 ? INT_MAX : nums2[j];
int left_max = max(left1, left2);
int right_min = min(right1, right2);
if(left_max <= right_min)
{
if((n1 + n2) % 2 == 1) return (double)left_max;
else return left_max / 2.0 + right_min / 2.0; // 分别除, 可能溢出
}
else if(right1 < left2) left = mid + 1;
else right = mid - 1;
}
return 0.0;
}
};
69. 有效的括号
cpp
class Solution
{
public:
bool isValid(string s)
{
unordered_map<char, char> m = {{'(', ')'}, {'[', ']'}, {'{', '}'}};
stack<char> st;
for(auto & e : s)
{
if(m.count(e)) st.push(e);
else
{
if(st.size())
{
char left = st.top();
if(e == m[left]) st.pop();
else return false;
}
else return false;
}
}
return st.empty();
}
};
70. 最小栈
维护前缀最小值
cpp
class MinStack
{
stack<pair<int, int>> st;
public:
MinStack(){};
void push(int value)
{
int preMin = INT_MAX;
if(st.size()) preMin = st.top().second;
st.emplace(value, min(preMin, value));
}
void pop()
{
st.pop();
}
int top()
{
return st.top().first;
}
int getMin()
{
return st.top().second;
}
};
/**
* Your MinStack object will be instantiated and called as such:
* MinStack* obj = new MinStack();
* obj->push(value);
* obj->pop();
* int param_3 = obj->top();
* int param_4 = obj->getMin();
*/
71. 字符串解码
cpp
class Solution
{
string _decodeString(string& s, int& i)
{
string ret;
int num = 0;
while(i < s.size())
{
char ch = s[i];
i++;
if(isalpha(ch)) ret += ch;
else if(isdigit(ch)) num = num * 10 + ch - '0';
else if(ch == '[')
{
// 注意递归调用过后, 需要更新 i 和重置 num
// 更新 i 通过传引用的方式
string t = _decodeString(s, i);
for(int k = 0; k < num; k++) ret += t;
num = 0;
}
else break;
}
return ret;
}
public:
string decodeString(string s)
{
int i = 0;
return _decodeString(s, i);
}
};
用栈模拟:
cpp
class Solution
{
public:
string decodeString(string s)
{
stack<pair<string, int>> st;
int i = 0;
int num = 0;
string ret;
string str;
while(i < s.size())
{
char ch = s[i];
i++;
if(isalpha(ch)) str += ch;
else if(isdigit(ch)) num = num * 10 + ch - '0';
else if(ch == '[')
{
st.emplace(str, num);
num = 0;
str = "";
continue;
}
else
{
string t = st.top().first;
int k = st.top().second;
st.pop();
for(; k > 0; k--) t += str;
str = t;
}
}
return str;
}
};
72. 每日温度
单调栈
比它大,单调减;比它小,单调增
找左边,正遍历;找右边,逆遍历
cpp
class Solution
{
public:
vector<int> dailyTemperatures(vector<int>& temperatures)
{
int n = temperatures.size();
vector<int> st;
vector<int> ret(n);
st.reserve(n);
for(int i = n - 1; i >= 0; i--)
{
while(st.size() && temperatures[st.back()] <= temperatures[i]) st.pop_back();
if(st.size()) ret[i] = st.back() - i;
else ret[i] = 0;
st.push_back(i);
}
return ret;
}
};
73. 柱状图中最大的矩形
单调栈
cpp
class Solution
{
vector<int> leftLastMin;
vector<int> rightLastMin;
public:
int largestRectangleArea(vector<int>& heights)
{
int n = heights.size();
leftLastMin.resize(n);
rightLastMin.resize(n);
stack<int> st;
for(int i = 0; i < n; i++)
{
while(st.size() && heights[st.top()] >= heights[i]) st.pop();
if(st.size()) leftLastMin[i] = st.top();
else leftLastMin[i] = -1;
st.push(i);
}
st = stack<int>();
for(int i = n - 1; i >= 0; i--)
{
while(st.size() && heights[st.top()] >= heights[i]) st.pop();
if(st.size()) rightLastMin[i] = st.top();
else rightLastMin[i] = n;
st.push(i);
}
int ret = 0;
for(int i = 0; i < n; i++)
{
ret = max(ret, heights[i] * (rightLastMin[i] - leftLastMin[i] - 1));
}
return ret;
}
};
优化:
cpp
class Solution
{
public:
int largestRectangleArea(vector<int>& heights)
{
int n = heights.size();
vector<int> st;
st.reserve(n + 1);
int ret = 0;
for(int i = 0; i <= n; ++i)
{
// 确保每一个位置都能弹栈, 即每一个高度都参与运算
int h = (i == n) ? 0 : heights[i];
while(st.size() && heights[st.back()] >= h)
{
// 如果进循环, 说明栈顶元素右边最近比它小的就是当前遍历到的下标, 左边最近比它小的就是栈顶的下一个
// 此时就可以直接在循环里计算以栈顶元素为高的最大矩形面积
int height = heights[st.back()];
st.pop_back();
int left = st.empty() ? -1 : st.back();
ret = max(ret, height * (i - left - 1));
}
st.push_back(i);
}
return ret;
}
};
74. 数组中的第K个最大元素
用堆:
cpp
class Solution
{
public:
int findKthLargest(vector<int>& nums, int k)
{
priority_queue<int, vector<int>, greater<int>> pq;
for (int x : nums)
{
if (pq.size() < k) pq.push(x);
else if (x > pq.top())
{
pq.pop();
pq.push(x);
}
}
return pq.top();
}
};
快速选择:类似于快速排序算法,随机数选 pivot + 左右指针
cpp
class Solution
{
mt19937 rng{random_device{}()};
int partition(vector<int>& nums, int left, int right)
{
uniform_int_distribution<int> dist(left, right);
int index = dist(rng);
int pivot = nums[index];
swap(nums[index], nums[left]);
int l = left;
left++;
while(1)
{
while(left <= right && nums[left] < pivot) left++;
while(left <= right && nums[right] > pivot) right--;
if(left >= right) break;
swap(nums[left], nums[right]);
left++;
right--;
}
swap(nums[right], nums[l]);
return right;
}
public:
int findKthLargest(vector<int>& nums, int k)
{
int n = nums.size();
int left = 0, right = nums.size() - 1;
int target = n - k;
while(left < right)
{
int i = partition(nums, left, right);
if(i == target) return nums[i];
else if(i < target) left = i + 1;
else right = i - 1;
}
return nums[left];
}
};
75. 前 K 个高频元素
堆
cpp
class Solution
{
class cmp
{
public:
bool operator()(const pair<int, int>& p1, const pair<int, int>& p2) const
{
return p1.second > p2.second;
}
};
public:
vector<int> topKFrequent(vector<int>& nums, int k)
{
unordered_map<int, int> mp;
for(int e : nums)
{
mp[e]++;
}
priority_queue<pair<int, int>, vector<pair<int, int>>, cmp> pq;
for(const auto& e : mp)
{
if(pq.size() < k) pq.emplace(e.first, e.second);
else if(e.second > pq.top().second)
{
pq.pop();
pq.emplace(e.first, e.second);
}
}
vector<int> ret;
ret.reserve(k);
for(int i = 0; i < k; i++)
{
int t = pq.top().first;
ret.push_back(t);
pq.pop();
}
return ret;
}
};
桶排序:
cpp
class Solution
{
public:
vector<int> topKFrequent(vector<int>& nums, int k)
{
int n = nums.size();
vector<vector<int>> buckets(n + 1);
unordered_map<int, int> mp;
mp.reserve(n);
for(int e : nums) mp[e]++;
for(auto& [ele, cnt] : mp) buckets[cnt].push_back(ele);
vector<int> ret;
ret.reserve(k);
for(int i = n, t = k; i > 0 && t > 0; i--)
{
for(int e : buckets[i])
{
ret.push_back(e);
t--;
if(t == 0) return ret;
}
}
return ret;
}
};
76. 数据流的中位数
cpp
class MedianFinder
{
priority_queue<int, vector<int>, less<int>> pqLeft;
priority_queue<int, vector<int>, greater<int>> pqRight;
public:
MedianFinder() = default;
void addNum(int num)
{
int n = pqLeft.size();
int m = pqRight.size();
if(n == m)
{
if(n == 0)
{
pqLeft.push(num);
return;
}
int midRight = pqRight.top();
if(num < midRight) pqLeft.push(num);
else
{
int t = pqRight.top(); pqRight.pop();
pqRight.push(num);
pqLeft.push(t);
}
}
else // n > m
{
int midLeft = pqLeft.top();
if(num > midLeft) pqRight.push(num);
else
{
int t = pqLeft.top(); pqLeft.pop();
pqLeft.push(num);
pqRight.push(t);
}
}
}
double findMedian()
{
int n = pqLeft.size();
int m = pqRight.size();
if(n == m) return (pqLeft.top() + pqRight.top()) / 2.0;
else return (double)pqLeft.top();
}
};
/**
* Your MedianFinder object will be instantiated and called as such:
* MedianFinder* obj = new MedianFinder();
* obj->addNum(num);
* double param_2 = obj->findMedian();
*/
77. 买卖股票的最佳时机
cpp
class Solution
{
public:
int maxProfit(vector<int>& prices)
{
int low = prices[0];
int ret = 0;
for(int p : prices)
{
if(p - low > ret) ret = p - low;
if(p < low) low = p;
}
return ret;
}
};
78. 跳跃游戏
cpp
class Solution
{
public:
bool canJump(vector<int>& nums)
{
int n = nums.size();
int farthest = 0;
for(int i = 0; i < n; i++)
{
if(i > farthest) return false;
farthest = max(farthest, i + nums[i]);
if(farthest >= n - 1) return true;
}
return false;
}
};
79. 跳跃游戏 II
left 记录每一次应该跳到的位置,这个位置就是能够到达最远处的那个位置。
cpp
class Solution
{
public:
int jump(vector<int>& nums)
{
int farthest = 0;
int step = 0;
int left = 0;
int n = nums.size();
while(farthest < n - 1)
{
int right = farthest;
for(int i = left; i < n && i <= right; i++)
{
if(i + nums[i] > farthest)
{
farthest = i + nums[i];
left = i;
}
}
step++;
}
return step;
}
};
每一次循环找到下一跳的最左端和最右端

cpp
class Solution
{
public:
int jump(vector<int>& nums)
{
int step = 0;
int left = 0, right = 0;
int farthest = 0;
int n = nums.size();
while(right < n - 1)
{
for(int i = left; i <= right; i++)
{
farthest = max(farthest, i + nums[i]);
}
left = right + 1;
right = farthest;
step++;
}
return step;
}
};
80. 划分字母区间
cpp
class Solution
{
public:
vector<int> partitionLabels(string s)
{
int n = s.size();
array<int, 26> lastExist;
for(int i = 0; i < n; i++)
{
lastExist[s[i] - 'a'] = i;
}
int left = 0, right = 0;
vector<int> ret;
ret.reserve(min(n, 26));
while(left < n)
{
for(int i = left; i <= right; i++)
{
right = max(right, lastExist[s[i] - 'a']);
}
ret.push_back(right - left + 1);
left = right + 1;
right = left;
}
return ret;
}
};
81. 爬楼梯
滚动数组
cpp
class Solution
{
public:
int climbStairs(int n)
{
if(n <= 3) return n;
int a = 1, b = 2, c = 0;
for(int i = 3; i <= n; i++)
{
c = a + b;
a = b;
b = c;
}
return c;
}
};
记忆化搜索
cpp
class Solution
{
int dp[46] = {0, 1, 2, 3};
public:
int climbStairs(int n)
{
if(dp[n]) return dp[n];
else
{
dp[n] = climbStairs(n - 1) + climbStairs(n - 2);
return dp[n];
}
}
};
矩阵快速幂:构造出矩阵相乘的形式
cpp
using LL = long long;
class Matrix
{
public:
Matrix() = default;
Matrix operator*(const Matrix& B) const
{
Matrix T = Matrix();
for(int i = 1; i <= 2; i++)
for(int p = 1; p <= 2; p++)
for(int j = 1; j <= 2; j++)
T[i][j] += (*this)[i][p] * B[p][j];
return T;
}
Matrix qpow(LL k) const
{
Matrix res = Matrix();
Matrix A = *this;
for(int i = 1; i <= 2; i++) res[i][i] = 1;
while(k)
{
if(k & 1) res = res * A;
A = A * A;
k >>= 1;
}
return res;
}
LL* operator[](int i) { return _matrix[i]; }
const LL* operator[](int i) const { return _matrix[i]; }
private:
LL _matrix[3][3];
};
class Solution
{
public:
int climbStairs(int n)
{
if(n <= 3) return n;
Matrix A = Matrix();
A[1][1] = 2, A[1][2] = 1;
Matrix B = Matrix();
B[1][1] = B[1][2] = B[2][1] = 1;
Matrix ans = A * B.qpow(n - 2);
return ans[1][1];
}
};
82. 杨辉三角
cpp
class Solution
{
public:
vector<vector<int>> generate(int numRows)
{
vector<vector<int>> dp(numRows);
for(int i = 0; i < numRows; ++i)
{
dp[i].resize(i + 1, 1);
for(int j = 1; j < i; ++j)
{
dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1];
}
}
return dp;
}
};
83. 打家劫舍
用两个 dp 数组:
cpp
class Solution
{
public:
int rob(vector<int>& nums)
{
int n = nums.size();
vector<int> dp1(n); // i 为结尾且偷 i
vector<int> dp2(n); // i 为结尾且不偷 i
dp1[0] = nums[0];
dp2[0] = 0;
for(int i = 1; i < n; i++)
{
dp1[i] = nums[i] + dp2[i - 1];
dp2[i] = max(dp1[i - 1], dp2[i - 1]);
}
return max(dp1[n - 1], dp2[n - 1]);
}
};
用一个:dpi 表示 0, i 区间上去偷能获得的最大金额,依赖于前两个位置
cpp
class Solution
{
public:
int rob(vector<int>& nums)
{
int n = nums.size();
vector<int> dp(n + 1);
dp[0] = 0, dp[1] = nums[0];
for(int i = 2; i <= n; i++)
{
dp[i] = max(dp[i - 1], dp[i - 2] + nums[i - 1]);
}
return dp[n];
}
};
空间优化:
cpp
class Solution
{
public:
int rob(vector<int>& nums)
{
int n = nums.size();
int a = 0, b = nums[0];
for(int i = 2; i <= n; i++)
{
int c = max(a + nums[i - 1], b);
a = b;
b = c;
}
return b;
}
};
// 用两个前置位
class Solution
{
public:
int rob(vector<int>& nums)
{
int n = nums.size();
int a = 0, b = 0;
for(int i = 0; i < n; i++)
{
int c = max(a + nums[i], b);
a = b;
b = c;
}
return b;
}
};
补充打家劫舍2:
cpp
class Solution
{
int _rob(const vector<int>& nums, int left, int right)
{
int a = 0, b = 0;
for(int i = left; i < right; i++)
{
int c = max(a + nums[i], b);
a = b;
b = c;
}
return b;
}
public:
int rob(vector<int>& nums)
{
int n = nums.size();
int t1 = _rob(nums, 1, n); // 不偷第一个
int t2 = _rob(nums, 2, n - 1); // 偷第一个
return max(t1, nums[0] + t2);
}
};
84. 完全平方数
完全背包
cpp
class Solution
{
public:
int numSquares(int n)
{
int k = sqrt(n);
vector<int> v(k + 1);
for(int i = 1; i <= k; i++) v[i] = i * i;
vector<vector<int>> dp(k + 1, vector<int>(n + 1));
for(int j = 1; j <= n; j++) dp[0][j] = 0x3f3f3f3f;
for(int i = 1; i <= k; i++)
{
for(int j = 1; j <= n; j++)
{
dp[i][j] = dp[i - 1][j];
if(j >= v[i]) dp[i][j] = min(dp[i][j], dp[i][j - v[i]] + 1);
}
}
return dp[k][n];
}
};
空间优化:
cpp
class Solution
{
public:
int numSquares(int n)
{
int k = sqrt(n);
vector<int> v(k + 1);
for(int i = 1; i <= k; i++) v[i] = i * i;
vector<int> dp(n + 1);
for(int j = 1; j <= n; j++) dp[j] = 0x3f3f3f3f;
for(int i = 1; i <= k; i++)
for(int j = v[i]; j <= n; j++)
dp[j] = min(dp[j], dp[j - v[i]] + 1);
return dp[n];
}
};
85. 零钱兑换
比上一个题多一个判断,本质一样。如果凑不出会发现格子里是 0x3f3f3f3f。
cpp
class Solution
{
public:
int coinChange(vector<int>& coins, int amount)
{
int n = coins.size();
vector<int> dp(amount + 1);
for(int j = 1; j <= amount; j++) dp[j] = 0x3f3f3f3f;
for(int i = 1; i <= n; i++)
for(int j = coins[i - 1]; j <= amount; j++)
dp[j] = min(dp[j], dp[j - coins[i - 1]] + 1);
return dp[amount] == 0x3f3f3f3f ? -1 : dp[amount];
}
};
86. 单词拆分
cpp
class Solution
{
public:
bool wordBreak(string s, vector<string>& wordDict)
{
int n = s.size();
vector<bool> dp(n, false); // [0, i] 的字串能否被拼接
unordered_set<string> mp(wordDict.begin(), wordDict.end());
for(int i = 0; i < n; i++)
{
// j == 0 的情况
if(mp.count(s.substr(0, i + 1)))
{
dp[i] = true;
continue;
}
for(int j = i; j > 0; j--)
{
// dp[j - 1] 放在左边判断, 利用 && 的短路特性可以减少 substr 的运算
dp[i] = dp[j - 1] && mp.count(s.substr(j, i - j + 1));
if(dp[i]) break;
}
}
return dp[n - 1];
}
};
87. 最长递增子序列
dp 解法
cpp
class Solution
{
public:
int lengthOfLIS(vector<int>& nums)
{
int n = nums.size();
vector<int> dp(n, 1); // 注意全部初始化为 1
int ret = 1;
for(int i = 1; i < n; i++)
{
for(int j = 0; j < i; j++)
{
if(nums[j] < nums[i])
{
dp[i] = max(dp[i], dp[j] + 1);
}
}
ret = max(ret, dp[i]);
}
return ret;
}
};
贪心 + 二分
cpp
class Solution
{
public:
int lengthOfLIS(vector<int>& nums)
{
int n = nums.size();
vector<int> tails; // tails[i] 记录长度为 i 的最长递增子序列的末尾元素
for(int x : nums)
{
auto it = lower_bound(tails.begin(), tails.end(), x); // 找第一个 >= x 的元素
if(it == tails.end()) tails.push_back(x);
else *it = x; // 由于 *it >= x, 所以能拼到 x 后面的元素都能拼到 *it 后面
}
return tails.size();
}
};
手写二分:
cpp
class Solution
{
int find(const vector<int>& tails, int x)
{
int left = 0, right = tails.size() - 1;
while(left < right)
{
int mid = left + (right - left) / 2;
if(tails[mid] < x) left = mid + 1;
else right = mid;
}
return tails[left] >= x ? left : -1;
}
public:
int lengthOfLIS(vector<int>& nums)
{
int n = nums.size();
vector<int> tails; // tails[i] 记录长度为 i 的最长递增子序列的末尾元素
tails.reserve(n);
for(int x : nums)
{
int index = find(tails, x);
if(index == -1) tails.push_back(x);
else tails[index] = x;
}
return tails.size();
}
};
88. 乘积最大子数组
维护一个乘积最大子数组和一个乘积最小子数组
cpp
class Solution
{
public:
int maxProduct(vector<int>& nums)
{
int n = nums.size();
vector<int> dp_max(nums);
vector<int> dp_min(nums);
int ret = nums[0];
for(int i = 1; i < n; i++)
{
dp_max[i] = max(nums[i], max(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i]));
dp_min[i] = min(nums[i], min(dp_max[i - 1] * nums[i], dp_min[i - 1] * nums[i]));
ret = max(ret, dp_max[i]);
}
return ret;
}
};
89. 分割等和子集
cpp
class Solution
{
public:
bool canPartition(vector<int>& nums)
{
int sum = 0;
for(int x : nums) sum += x;
if(sum & 1) return false;
int target = sum / 2;
int n = nums.size();
vector<vector<bool>> dp(n + 1, vector<bool>(target + 1, false));
for(int i = 0; i <= n; i++) dp[i][0] = true;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= target; j++)
{
dp[i][j] = dp[i - 1][j];
if(j >= nums[i - 1]) dp[i][j] = dp[i][j] || dp[i - 1][j - nums[i - 1]];
}
}
return dp[n][target];
}
};
空间优化,注意 01 背包的空间优化要倒序
cpp
class Solution
{
public:
bool canPartition(vector<int>& nums)
{
int sum = 0;
for(int x : nums) sum += x;
if(sum & 1) return false;
int target = sum / 2;
int n = nums.size();
vector<bool> dp(target + 1);
dp[0] = true;
for(int i = 1; i <= n; i++)
for(int j = target; j >= nums[i - 1]; j--)
dp[j] = dp[j] || dp[j - nums[i - 1]];
return dp[target];
}
};
bitset 优化:
cpp
class Solution
{
public:
bool canPartition(vector<int>& nums)
{
int sum = accumulate(nums.begin(), nums.end(), 0);
if (sum & 1) return false;
int target = sum / 2;
bitset<10001> dp;
dp[0] = 1;
for (int x : nums)
{
// 一次左移 + 或运算就可以把所有位都计算了, 相当于上面的一层循环
dp |= dp << x; // 注意在 bitset 中相对于数组是反着存储的, 因此这里是左移
if (dp[target]) return true;
}
return false;
}
};
90. 最长有效括号
dp:如果为 ( 则压栈,dpi 为 0;如果为 ) 则看最近匹配的 ( (其下标记为 index) 并计算长度再 + dpindex - 1
cpp
class Solution
{
public:
int longestValidParentheses(string s)
{
int n = s.size();
vector<int> st;
vector<int> dp(n, 0);
int ret = 0;
for(int i = 0; i < n; i++)
{
if(s[i] == '(') st.push_back(i);
else
{
if(st.empty()) continue;
int index = st.back(); st.pop_back();
dp[i] = i - index + 1;
if(index > 0) dp[i] += dp[index - 1];
ret = max(ret, dp[i]);
}
}
return ret;
}
};
左右扫描
cpp
class Solution {
public:
int longestValidParentheses(string s) {
int left = 0, right = 0;
int ret = 0;
// 从左到右
for (char c : s)
{
if (c == '(') left++;
else right++;
if (left == right) ret = max(ret, 2 * right);
else if (right > left) left = right = 0;
}
left = right = 0;
// 从右到左
for (int i = (int)s.size() - 1; i >= 0; i--)
{
if (s[i] == '(') left++;
else right++;
if (left == right) ret = max(ret, 2 * left);
else if (left > right) left = right = 0;
}
return ret;
}
};
91. 不同路径
cpp
class Solution
{
public:
int uniquePaths(int m, int n)
{
vector<int> dp(n, 1);
for(int i = 1; i < m; i++)
for(int j = 1; j < n; j++)
dp[j] += dp[j - 1];
return dp[n - 1];
}
};
92. 最小路径和
cpp
class Solution
{
public:
int minPathSum(vector<vector<int>>& grid)
{
int r = grid.size(), c = grid[0].size();
vector<vector<int>> dp(r + 1, vector<int>(c + 1, 0x3f3f3f3f));
dp[0][1] = 0;
for(int i = 1; i <= r; i++)
for(int j = 1; j <= c; j++)
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1];
return dp[r][c];
}
};
cpp
class Solution
{
public:
int minPathSum(vector<vector<int>>& grid)
{
int r = grid.size(), c = grid[0].size();
const int INF = 0x3f3f3f3f;
vector<int> dp(c + 1, INF);
dp[1] = 0;
for (int i = 1; i <= r; i++)
for (int j = 1; j <= c; j++)
dp[j] = min(dp[j], dp[j - 1]) + grid[i - 1][j - 1];
return dp[c];
}
};
93. 最长回文子串
dp 解法
cpp
class Solution
{
public:
string longestPalindrome(string s)
{
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
int begin = 0, maxLen = 0;
for(int i = n - 1; i >= 0; i--)
{
for(int j = i; j < n; j++)
{
if(s[i] == s[j])
{
if(i + 1 >= j) dp[i][j] = true;
else dp[i][j] = dp[i + 1][j - 1];
if(dp[i][j] && j - i + 1 > maxLen)
{
maxLen = j - i + 1;
begin = i;
}
}
}
}
return s.substr(begin, maxLen);
}
};
中心扩展:
cpp
class Solution
{
pair<int, int> extend(string& s, int left, int right)
{
int n = s.size();
int begin = 0, maxLen = 0;
while(left >= 0 && right < n && s[left] == s[right])
{
left--;
right++;
}
if(right - left - 1 > maxLen)
{
begin = left + 1;
maxLen = right - left - 1;
}
return {begin, maxLen};
}
public:
string longestPalindrome(string s)
{
int n = s.size();
int begin = 0, maxLen = 0;
for(int i = 0; i < n; i++)
{
auto [x, y] = extend(s, i, i);
if(y > maxLen)
{
begin = x;
maxLen = y;
}
}
for(int i = 0; i < n - 1; i++)
{
auto [x, y] = extend(s, i, i + 1);
if(y > maxLen)
{
begin = x;
maxLen = y;
}
}
return s.substr(begin, maxLen);
}
};
94. 最长公共子序列
dp + 空间优化
cpp
class Solution
{
public:
int longestCommonSubsequence(string text1, string text2)
{
int n = text1.size(), m = text2.size();
vector<int> dp(m + 1);
for(int i = 1; i <= n; i++)
{
int pre = 0;
for(int j = 1; j <= m; j++)
{
int tmp = dp[j]; // 注意这里是 dp[j] 而不是 dp[j - 1], 因为对于下一个循环来说当前的 j 就是 j - 1
if(text1[i - 1] == text2[j - 1]) dp[j] = pre + 1; // 这一步需要上一行左侧的信息
else dp[j] = max(dp[j], dp[j - 1]); // 这一步需要当前行左侧更新后和上一行的信息
// 因此一个需要倒着遍历, 一个需要正遍历, 需要额外存储上一行信息
pre = tmp;
}
}
return dp[m];
}
};
95. 编辑距离
cpp
class Solution
{
public:
int minDistance(string word1, string word2)
{
int n = word1.size(), m = word2.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1));
for(int i = 1; i <= n; i++) dp[i][0] = i;
for(int j = 1; j <= m; j++) dp[0][j] = j;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
{
if(word1[i - 1] == word2[j - 1]) dp[i][j] = dp[i - 1][j - 1];
// 插入 删除 修改
else dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1])) + 1;
}
}
return dp[n][m];
}
};
96. 只出现一次的数字
cpp
class Solution
{
public:
int singleNumber(vector<int>& nums)
{
int ret = 0;
for(auto& e : nums) ret ^= e;
return ret;
}
};
97. 多数元素
摩尔投票
cpp
class Solution
{
public:
int majorityElement(vector<int>& nums)
{
int curWin = 0, cnt = 0;
for(int x : nums)
{
if(cnt == 0) curWin = x;
if(x == curWin) cnt++;
else cnt--;
}
return curWin;
}
};
98. 颜色分类
有点类似于移动 0
cpp
class Solution
{
public:
void sortColors(vector<int>& nums)
{
int n = nums.size();
int left = -1, right = n;
for(int i = 0; i < right; i++)
{
while(nums[i] != 1 && i > left && i < right)
{
if(nums[i] == 0) swap(nums[i], nums[++left]);
else swap(nums[i], nums[--right]);
}
}
}
};
99. 下一个排列
cpp
class Solution
{
public:
void nextPermutation(vector<int>& nums)
{
int n = nums.size();
// 从右到左找第一个可以增大的数 x
int index = -1;
for(int i = n - 1; i >= 1; i--)
{
if(nums[i] > nums[i - 1])
{
index = i - 1;
break;
}
}
// 在 [index + 1, n - 1] 中找大于 x 且距离 x 最近的数, 因为只要大一点点就行了
// 这里也可以线性查找, 不一定用二分, 反正最后时间复杂度都是 O(n)
if(index >= 0)
{
int left = index + 1, right = n - 1;
int x = nums[index];
while(left < right)
{
int mid = left + (right - left + 1) / 2;
if(nums[mid] <= x) right = mid - 1;
else left = mid;
}
swap(nums[index], nums[left]);
}
// 反转 index 之后的子数组
for(int left = index + 1, right = n - 1; left < right; left++, right--) swap(nums[left], nums[right]);
}
};
100. 寻找重复数
用类似于找环形链表的入口的做法:
cpp
class Solution
{
public:
int findDuplicate(vector<int>& nums)
{
int fast = nums[0], slow = nums[0];
do
{
slow = nums[slow];
fast = nums[nums[fast]];
} while(slow != fast);
// 再找环的入口
slow = nums[0];
while(slow != fast)
{
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
};