[Leetcode]239.sliding Window Maximum

Source: Internet
Author: User

Topic

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.

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?

Ideas

If brute force method is used, the problem seems to be easy to solve: You can scan all the numbers of each sliding window and find the maximum value. If the size of the sliding window is K, an O (k) time is required to find the maximum value in the sliding window. For an input array of length n, the total time complexity of the algorithm is O (NK).
Actually a sliding window can be seen as a queue. When the window is sliding, the first number in the window is deleted, and a new number is added at the end of the window. This conforms to the FIFO feature of the queue. If we can find out the maximum number of it from the queue, this problem will be solved.
We implemented a stack that can get the minimum value with O (1) time. Also, the maximum value of the stack can be obtained with O (1) time. We also discussed how to implement a queue with two stacks. Combining these two problems, we found that if the queue is implemented with two stacks, because the maximum value in the stack can be obtained with O (1) time, the maximum value of the queue can be obtained with O (1) time, so the total time complexity is reduced to O (n). We can use this method to solve the problem. However, this is equivalent to a round of interview time to do two face questions, not enough time. Let's see if there's any other way.
Here's a different idea. We do not put each value of the sliding window into the queue, but only the values that are likely to be the maximum value of the sliding window are deposited into a queue with open ends. Next, take the input number {2,3,4,2,6,2,5,1} as an example step analysis.
The first number of the array is 2, put it in the queue. The second number is 3. Since it is 2 larger than the previous number, 2 cannot be the maximum value in a sliding window. 2 first delete from the queue, and then put 3 into the queue. There is only one number in the queue 3. The steps for the third number 4 are similar, and eventually only one digit 4 is left in the queue. The sliding window already has 3 digits, and its maximum value is 4 in the head of the queue.
Next, the fourth digit 2 is processed. 2 is smaller than the number 4 in the queue. When 4 slides out of the window 2 is still likely to be the maximum value of the sliding window, so put 2 in the tail of the queue. There are now two digits 4 and 2 in the queue, where the maximum value of 4 is still in the head of the queue.
The next number is 6. Since it is larger than the number 4 and 2 already in the queue, then 4 and 2 are unlikely to be the maximum values in the sliding window. First remove 4 and 2 from the queue, and then put the number 6 in the queue. At this time the maximum value of 6 is still in the head of the queue.
The sixth number is 2. Since it is smaller than the number 6 already in the queue, 2 is also credited to the tail of the queue. There are two numbers in the queue, with a maximum of 6 bits in the head of the queue.
The next number is 5. In the queue of two digits 6 and 2, 2 is less than 5, so 2 cannot be the maximum value of a sliding window, you can remove it from the tail of the queue. After the number 2 is deleted, the number 5 is saved to the queue. At this point there are two digits in the queue, 6 and 5, where the head of the queue is the maximum value of 6.
The last digit of the array is 1, which puts 1 in the tail of the queue. Note that the number 6 at the head of the queue is the 5th number in the array, and the sliding window does not include the number, so the number 6 should be removed from the queue. So how do you know if a sliding window includes a number? should be inThe subscript in the queue where numbers are stored in the array, not the valuesWhen the subscript of a number is greater than or equal to the size of the number being processed, the number has been slid out of the sliding window and can be removed from the queue.

Code

/ *---------------------------------------* Date: 2015-07-19* sjf0115* title: 239.Sliding Window maximum* website: https:// leetcode.com/problems/sliding-window-maximum/* Result: ac* Source: leetcode* Blog:-----------------------------------------*/ #include <iostream>#include <vector>#include <deque>using namespace STD;classSolution { Public: vector<int>Maxslidingwindow ( vector<int>& Nums,intK) { vector<int>ResultintSize = Nums.size ();if(Size <=0|| K <=0){returnResult }//if        //bidirectional queue         deque<int> deque; for(inti =0; I < K1; ++i) {//delete values less than or equal to the current element such as 4 2 1 5             while(!deque. Empty () && Nums[i] >= nums[deque. Back ()]) {deque. Pop_back (); }//while            deque. push_back (i); }//for        //shortage of K        if(Size < K) {Result.push_back (nums[deque. Front ()]); }//if         for(inti = k1; i < size;++i) {//delete values less than or equal to the current element             while(!deque. Empty () && Nums[i] >= nums[deque. Back ()]) {deque. Pop_back (); }//while            //not within sliding window             while(!deque. Empty () && I-deque. Front () >= k) {deque. Pop_front (); }//while            deque. push_back (i); Result.push_back (nums[deque. Front ()]); }//for        returnResult }};intMain () {solution S;intK =3; vector<int>VEC = {4,1,3};//,-1,-2,-3,5,3,6,7     vector<int>result = S.maxslidingwindow (vec,k); for(inti =0; i < result.size (); ++i) {cout<<result[i]<<" "; }//for    cout<<endl;return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[leetcode]239.sliding Window Maximum

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.