diff --git a/include/jianzhi_offer.h b/include/jianzhi_offer.h index 19a3f72..3c4af8e 100644 --- a/include/jianzhi_offer.h +++ b/include/jianzhi_offer.h @@ -115,4 +115,14 @@ private: std::stack _min_stk; }; +/** + * 剑指 Offer 59 - I. 滑动窗口的最大值 + * + * @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/58o46i/ + * @param nums + * @param k + * @return + */ +std::vector max_sliding_window(std::vector& nums, int k); + } \ No newline at end of file diff --git a/src/jianzhi_offer/number.cpp b/src/jianzhi_offer/number.cpp new file mode 100644 index 0000000..9f8a3ab --- /dev/null +++ b/src/jianzhi_offer/number.cpp @@ -0,0 +1,19 @@ +#include "jianzhi_offer.h" + +namespace yaha { +std::vector max_sliding_window(std::vector &nums, int k) { + std::vector 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; +} +} \ No newline at end of file diff --git a/tests/jianzhi_offer/number_test.cpp b/tests/jianzhi_offer/number_test.cpp new file mode 100644 index 0000000..58c32e2 --- /dev/null +++ b/tests/jianzhi_offer/number_test.cpp @@ -0,0 +1,16 @@ +#include "jianzhi_offer.h" + +#include "gtest/gtest.h" + +TEST(MaxSlidingWindowTest, NumbaerTest) { + std::vector nums = {1, 3, -1, -3, 5, 3, 6, 7}; + int k = 3; + auto res = yaha::max_sliding_window(nums, k); + std::vector exp = {3, 3, 5, 5, 6, 7}; + ASSERT_EQ(exp, res); + + std::vector nums2 = {1, -1}; + std::vector exp2 = {1, -1}; + res = yaha::max_sliding_window(nums, k); + ASSERT_EQ(exp2, res); +} \ No newline at end of file