NO64、滑动窗口的最大值(经典,越到最后越经典)

64、滑动窗口的最大值

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
窗口大于数组长度的时候,返回空
示例1
输入

[2,3,4,2,6,2,5,1],3

返回值

[4,4,6,6,6,5]

1、自己想的,边界条件很多

总的来说,利用 low high maxIndex三个指针维护整个数组的情况

1、滑动窗口大小为0,num数组为空,滑动窗口大于 num.size 也不符合规矩,直接返回空

2、先考虑第一个滑动窗口的情况,走一遍,找出最大值的index

 vector<int> maxInWindows(const vector<int>& num, unsigned int size)
    {
    vector<int> result;
    if (num.size() == 0 || size == 0 || size > num.size()) return result;
    if (size == num.size()) {
        result.push_back(*max_element(num.begin(), num.end())); 
         return result;
      }

    int low = 0, high = size - 1, maxIndex = 0;
    int len = num.size();
    for (int i = 0; i <= high; ++i) {
        if (num[i] > num[maxIndex])  maxIndex = i;
    }
    //result.push_back(num[maxIndex]); //这里不能直接先push,要不然第一个滑动窗口的最大值会push两次
    while (high <= len - 1) {
        if (maxIndex == low - 1) {//如果maxIndex还是上个窗口的最低索引,需要更新
            maxIndex = low;
            for (int i = low; i <= high; ++i)
                if (num[i] > num[maxIndex])  maxIndex = i;

        }
        else if (num[maxIndex] < num[high]) //如果最新添加进来的high索引比原窗口中的所有值都要大,也要更新
        {
            maxIndex = high;
        }
        high++;
        low++;

        result.push_back(num[maxIndex]);

    }
    return result;
    }
2、第二种做法,比较水,借助优先队列来做,大顶堆
vector<int> maxInWindows(const vector<int>& num, unsigned int size)
{
    vector<int> result;
    if (num.size() == 0 || size == 0 |

剩余60%内容,订阅专栏后可继续查看/也可单篇购买

带你刷完67道剑指offer 文章被收录于专栏

- 本专栏汇集了67道剑指offer的一些精妙解法,不少题有5-6种解法之多,有些题目二刷三刷的解法也不一样。 - 本专栏帮助我拿到6个互联网大厂offer,最终圆梦字节跳动公司。

全部评论
两位大佬
1 回复 分享
发布于 2021-02-13 13:30
一刷的解法二中有笔误,priority_queue<int> pq 是大顶堆,二刷的更正了。</int>
1 回复 分享
发布于 2021-01-26 15:49

相关推荐

11-06 16:50
门头沟学院 Java
用微笑面对困难:word打字比赛二等奖的我,也要来凑合凑合
点赞 评论 收藏
分享
明天不下雨了:这个项目 这个简历 这个模板 莫不是一个开源的
点赞 评论 收藏
分享
评论
3
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务