剑指 Offer 59 - I 滑动窗口的最大值
概述
https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/
https://leetcode.com/problems/sliding-window-maximum/
暴力遍历
遍历所有的起始端点。
实现的时候注意两点:
- 注意内层 for 循环的条件是
j < i + k
,没有等于号哦。 - 注意 nums 为空的情况。
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> ans;
if (nums.size() == 0) return ans;
for (int i = 0; i + k <= nums.size(); i ++) {
int tmp = INT_MIN;
for (int j = i; j < i + k; j ++) {
tmp = max(tmp, nums[j]);
}
ans.push_back(tmp);
}
return ans;
}
};
Links: sword-offer-59-1