剑指offer-64.滑动窗口的最大值

来源:互联网 发布:mac os stm8 编辑:程序博客网 时间:2024/04/28 20:59

题目:给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{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]}。


思路:找出滑动窗口的边界,把窗口第一个数附为最大值,在窗口内进行循环,然后比较窗口内数的大小,


class Solution {public:    vector<int> maxInWindows(const vector<int>& num, unsigned int size)    {        int length = num.size();        vector<int>res;        if (length < size || size == 0)        {            return res;        }        int max = 0;        for (int i = 0; i <= length - size; i++)        {            max = num[i];            for (int j = i + 1; j < i + size; j++)            {                if (max < num[j])                    max = num[j];            }            res.push_back(max);        }        return res;    }};



0 0