239. Sliding Window Maximum

Source: Internet
Author: User

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?

Similar:

Minimum Window Substring

155. Min Stack

159. Longest Substring with at most Distinct characters

265. Paint House II

1Solution 1. Priority Queue2  Public classSolution {3     classPairImplementsComparable<pair>{4          Public intkey;5          Public intidx;6         7          PublicPair (intKintID) {8              This. Key =K;9              This. idx =ID;Ten         } One          A @Override -          Public intcompareTo (Pair p) { -             return  This. Key < P.key? 1: ( This. Key = = P.key? 0:-1);//reverse order, from Large to Small the         } -     } -      -      Public int[] Maxslidingwindow (int[] Nums,intk) { +         if(Nums.length = = 0 | | k <= 0)return New int[0]; -          +Priorityqueue<pair> que =NewPriorityqueue<pair>(); A         int[] ret =New int[Nums.length-k + 1]; at         inti = 0; -          -          for(i = 0; i < nums.length; i++) { -Que.add (NewPair (Nums[i], i)); -              while(Que.peek (). idx < I-k + 1) { - Que.poll (); in             } -             if(I >= k-1) { toRET[I-K+1] =Que.peek (). Key; +             } -         } the          *         returnret; $     }Panax Notoginseng}

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.