滑动窗口
This commit is contained in:
parent
81da2f5b17
commit
e23d7c213b
@ -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);
|
||||
|
||||
}
|
||||
19
src/jianzhi_offer/number.cpp
Normal file
19
src/jianzhi_offer/number.cpp
Normal 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;
|
||||
}
|
||||
}
|
||||
16
tests/jianzhi_offer/number_test.cpp
Normal file
16
tests/jianzhi_offer/number_test.cpp
Normal 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);
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user