LeetCode OJ Algorithm – Sliding Window Maximum(hard)

看到此文,是否觉得体内洪荒之力爆发,饥渴难耐想吐槽、情不自禁想捐赠
本文为原创文章,尊重辛勤劳动,可以免费摘要、推荐或聚合,亦可完整转载,但完整转载需要标明原出处,违者必究。

支付宝微  信

原题

Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.

For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Max
---------------               -----
[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

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note:
You may assume k is always valid, ie: 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?

地址

https://leetcode.com/problems/sliding-window-maximum/

程序范例

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        int rLength = nums.size() - k + 1;
        if (nums.size() == 0) {
            vector<int> r(0,0);
            return r;
        }
        vector<int> r(rLength,-999999999);
        vector<int>::iterator item = nums.begin();
        int index = 0;
        while(item != nums.end()) {
            for (int j = index; (j >= 0 && j >= index + 1 - k); j--) {
                if (j >= rLength) {
                    continue;
                }
                r[j] = max(r[j], *item);
            }
            ++index;
            ++item;
        }
        return r;
    }
};

程序运行分布图

Sliding Window Maximum 运行分布图

Sliding Window Maximum 运行分布图

看来,大部分的运行时间在80ms左右,而上述代码的运行时间却在500ms,必须优化。看原题提示:

 How about using a data structure such as deque (double-ended queue)?

未完待续。。。


文章来源:胡旭博客

转载请注明出处,违者必究!


这是一篇原创文章,如果您觉得有价值,可以通过捐赠来支持我的创作~
捐赠者会展示在博客的某个页面,钱将会用在有价值的地方,思考中...


分类: C/C++, 技术, 算法, 编程 | 标签: , , , | 评论 | Permalink

发表评论

电子邮件地址不会被公开。