滑动窗口

This commit is contained in:
yaha 2023-05-30 20:55:44 +08:00
parent 81da2f5b17
commit e23d7c213b
3 changed files with 45 additions and 0 deletions

View File

@ -115,4 +115,14 @@ private:
std::stack<int> _min_stk;
};
/**
* Offer 59 - I.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/58o46i/
* @param nums
* @param k
* @return
*/
std::vector<int> max_sliding_window(std::vector<int>& nums, int k);
}

View File

@ -0,0 +1,19 @@
#include "jianzhi_offer.h"
namespace yaha {
std::vector<int> max_sliding_window(std::vector<int> &nums, int k) {
std::vector<int> ret;
for (int i = 0; i < nums.size(); i++) {
int max_num = 0;
if (k + i <= nums.size()) {
for (int j = i; j < k + i; ++j) {
std::cout << nums[j] << " " << std::endl;
max_num = std::max(max_num, nums[j]);
}
ret.push_back(max_num);
}
}
return ret;
}
}

View File

@ -0,0 +1,16 @@
#include "jianzhi_offer.h"
#include "gtest/gtest.h"
TEST(MaxSlidingWindowTest, NumbaerTest) {
std::vector<int> nums = {1, 3, -1, -3, 5, 3, 6, 7};
int k = 3;
auto res = yaha::max_sliding_window(nums, k);
std::vector<int> exp = {3, 3, 5, 5, 6, 7};
ASSERT_EQ(exp, res);
std::vector<int> nums2 = {1, -1};
std::vector<int> exp2 = {1, -1};
res = yaha::max_sliding_window(nums, k);
ASSERT_EQ(exp2, res);
}