Hard 239题 Sliding Window Maximum

来源:互联网 发布:建筑学书籍知乎 编辑:程序博客网 时间:2024/06/03 12:00

Question;

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 thek 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.

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.

Follow up:
Could you solve it in linear time?

Hint:

  1. How about using a data structure such as deque (double-ended queue)?
  2. The queue size need not be the same as the window’s size.
  3. Remove redundant elements and the queue should store only elements that need to be considered.

Solution:

TLE做法

public class Solution {   public static int[] maxSlidingWindow(int[] nums, int k) {                if(nums.length==0||nums==null||k==0)            return new int[0];        Deque<Integer> dq=new LinkedList<Integer>();        int[] res=new int[nums.length-k+1];                for(int i=0;i<=k-1;i++)            dq.offerLast(nums[i]);        res[0]=max_in_dq(dq);        for(int i=1;i<=nums.length-k;i++){            dq.pollFirst();            dq.offerLast(nums[i+k-1]);            res[i]=max_in_dq(dq);        }        for(int i=0;i<=res.length-1;i++)        System.out.print(res[i]);        return res;    }    public static int max_in_dq(Deque<Integer> dq){        int ans=((LinkedList<Integer>) dq).get(0);        for(int i=1;i<=dq.size()-1;i++){            if(((LinkedList<Integer>) dq).get(i)>ans)                ans=((LinkedList<Integer>) dq).get(i);        }        return ans;    }}

 discussion结论

public class Solution {   public static int[] maxSlidingWindow(int[] nums, int k) {        if(nums.length==0||nums==null||k==0)            return new int[0];        int[] res = new int[nums.length-k+1];Deque<Integer> dq=new ArrayDeque<Integer>();//store the index        for(int i=0;i<=nums.length-1;i++){            // remove numbers out of range kif (!dq.isEmpty() && dq.peekFirst() < i - k + 1) {dq.pollFirst();}// remove smaller numbers in k range as they are useless            while(!dq.isEmpty()&&nums[i]>nums[dq.peekLast()])                dq.pollLast();            dq.offerLast(i);              if(i+1>=k) res[i-k+1] = nums[dq.getFirst()];          }      return res;     }}




0 0
原创粉丝点击