Given an array nums, there is a sliding window of size K which are moving from the very left of the array To the very right. You can only see the K numbers in the window. Each of 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 are always valid, Ie:1≤k≤input array's size for non-empty array.
Follow up:
Could solve it in linear time?
Analyse:find the maximum in each window and push it into the result vector.
Runtime:340ms.
1 classSolution {2 Public:3vector<int> Maxslidingwindow (vector<int>& Nums,intk) {4vector<int>result;5 if(nums.size () = =0)returnresult;6 7 intleft =0, right = K-1;8 while(Right <nums.size ()) {9 inttemp = int_min;//maximum in the current windowTen if(left = right) temp =Nums[left]; One Else{ A for(inti = left; I <= right; i++) -temp =Max (temp, nums[i]); - } the Result.push_back (temp); -left++; -right++; - } + returnresult; - } +};
Sliding Window Maximum