【leetCode】Sliding Window Maximum【求高人解释】

来源:互联网 发布:淘宝助理水印图片大小 编辑:程序博客网 时间:2024/06/08 08:34

</pre>Given an array <span style="">nums</span>, there is a sliding window of size <span style="">k</span> which is moving from the very left of the array to the very right. You can only see the <span style="">k</span> numbers in the window. Each time the sliding window moves right by one position.<p></p><p style="margin-top:0px; margin-bottom:10px; color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Arial,sans-serif; font-size:14px; line-height:30px">For example,<br style="" />Given <span style="">nums</span> = <code style="font-family:Menlo,Monaco,Consolas,'Courier New',monospace; font-size:13px; padding:2px 4px; color:rgb(199,37,78); background-color:rgb(249,242,244)">[1,3,-1,-3,5,3,6,7]</code>, and <span style="">k</span> = 3.</p><pre style="overflow:auto; font-family:Menlo,Monaco,Consolas,'Courier New',monospace; font-size:13px; padding:9.5px; margin-top:0px; margin-bottom:10px; line-height:1.42857143; color:rgb(51,51,51); word-break:break-all; word-wrap:break-word; background-color:rgb(245,245,245); border:1px solid rgb(204,204,204)">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.

发这个帖子的主要原因是LeetCode给的这个测试用例:


难道输出不应该是[1,1]么?还是我对题目理解有误?

附上我的代码:

class Solution {public:vector<int> maxSlidingWindow(vector<int>& nums, int k) {int  max = 0;vector<int> r;//结果vectorvector<int>::size_type length = nums.size();//如果传入数组为空if (nums.size() == 0 || k<1)return r;//如果nums的长度小于等于K,就直接取得整个nums的最大值if (nums.size() <= k){max = nums[0];for (decltype(length) i = 0; i < length; i++){max = nums[i]>max ? nums[i] : max;}r.push_back(max);return r;}else{decltype(length) pos = 0;max = nums[0];vector<int>::size_type maxPos = 0;//如果当前窗口的最后一个位置没有超过vector最后一个元素//第一步:初始化,首先找到第一个Max和MaxPosfor (vector<int>::size_type i = 0; i <= pos + k - 1; i++){if (nums[i] > max){max = nums[i];maxPos = i;}}//第二步:依次向后移动窗口,每次判断下MaxPos是否在新窗口中,在的话就直接拿新进入窗口的值跟Max比较//        否则重新选取Maxwhile ((pos + k - 1) < length){if ((pos) <= maxPos < (pos + k - 1)){if (nums[pos + k - 1]>max)max = nums[pos + k - 1];}else{for (vector<int>::size_type i = 0; i <= pos + k - 1; i++){if (nums[i] > max){max = nums[i];maxPos = i;}}}r.push_back(max);pos++;}return r;}}};


0 0
原创粉丝点击