1. 和为 K 的子数组
题目来源
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的子数组的个数 。子数组是数组中元素的连续非空序列。
示例 1:
输入:nums = [1,1,1], k = 2
输出:2
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int, int> hash;
int sum = 0;
int ret = 0;
hash[0] = 1;
// 前缀和
for (auto & n : nums){
sum += n;
if (hash.count(sum - k)) ret += hash[sum - k];
hash[sum]++;
}
return ret;
}
};
2. 滑动窗口最大值
题目来源
给你一个整数数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。返回 滑动窗口中的最大值 。
示例 1:
输入:nums = [1,3,-1,-3,5,3,6,7], k = 3
输出:[3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
int n = nums.size();
priority_queue<pair<int, int>> q;
for (int i = 0; i < k; ++i){
q.push({nums[i], i});
}
vector<int> ret;
ret.push_back(q.top().first);
for (int i = k; i < n; ++i){
// 单调队列,根据他们的下标
while (!q.empty() && i - k >= q.top().second) q.pop();
q.push({nums[i], i});
ret.push_back(q.top().first);
}
return ret;
}
};
3. 最小覆盖子串
题目来源
给你一个字符串 s 、一个字符串 t 。返回 s 中涵盖 t 所有字符的最小子串。如果 s 中不存在涵盖 t 所有字符的子串,则返回空字符串 “” 。
注意:
对于 t 中重复字符,我们寻找的子字符串中该字符数量必须不少于 t 中该字符数量。
如果 s 中存在这样的子串,我们保证它是唯一的答案。
示例 1:
输入:s = “ADOBECODEBANC”, t = “ABC”
输出:“BANC”
解释:最小覆盖子串 “BANC” 包含来自字符串 t 的 ‘A’、‘B’ 和 ‘C’。
class Solution {
public:
string minWindow(string s, string t) {
unordered_map<int, int> hash;
for (auto & c : t) hash[c]++;
int n = s.size();
int left = 0, right = 0;
int l = 0, r = n - 1;
int count = hash.size();
bool flag = false;
// 滑动窗口
while (right < n){
hash[s[right]]--;
if (hash[s[right]] == 0) count--;
while (count == 0){
flag = true;
if (right - left < r - l){
l = left, r = right;
}
hash[s[left]]++;
if (hash[s[left]] > 0) ++count;
++left;
}
++right;
}
if (flag) return s.substr(l, r - l + 1);
return "";
}
};
608

被折叠的 条评论
为什么被折叠?



