"Leetcode" Sliding window Maximum

Source: Internet
Author: User

Title Link: https://leetcode.com/problems/sliding-window-maximum/

Topic:
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?

Ideas:
It was hard, indeed. Want to do O (N) solution did not think out, looked at the online thinking, the results found. Also O (n*k) ... The Pit-daddy?

Algorithm:

    Public int[]Maxslidingwindow(int[] Nums,intK) {if(k==0)return New int[0];intRes[] =New int[Nums.length-k +1]; Linkedlist<integer> IDXS =NewLinkedlist<integer> (); for(inti =0; i < nums.length; i++) { while(!idxs.isempty () && nums[i] >=nums[idxs.getlast ()) {//Delete all elements within the window that are less than the element I will enterIdxs.removelast ();//Because I is the newest element in the window, the element smaller than it certainly kicks out of the window sooner than it} idxs.addlast (i);if(I-idxs.getfirst () +1> k) {Idxs.removefirst (); }if(i +1>= k) res[i-k+1] = Nums[idxs.getfirst ()]; }returnRes }

"Leetcode" 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.