239. Sliding Window Maximum/ min https://www.youtube.com/watch?v=2SXqBsTR6a8 https://www.youtube.com/watch?v=G70qltIBF40 过例子, 写自己的 思路, 然后写自己的代码 class Solution { public int[] maxSlidingWindow(int[] nums, int k) { Deque<Integer> deque = new LinkedList<>(); List<Integer> result = new ArrayList<>(); for(int i = 0; i < nums.length; i++){ while(!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]){ deque.pollLast(); // if deque is not empty and the new coming elements is bigger than the element at the end of the deque, then we pop them from the end. the reason that we pop elements from the back is because, the deque is in decreasing order, which means, example, in this example, i use the value , instead of index. but its the same since we refer to nums[index]. : [6, 4,] if the new coming element is 5, then we need to pop 4 out of the deque and still keep 6 . if we pop them from the front, there is no way we can pop 4 from the deque. } deque.offerLast(i); // offer the new element, no matter if its smaller or bigger, because it has the potential to be the max later if(i - k + 1 >= 0){ // after index k - 1, its guarentted that we have a window of size k, so we output a max value to the result everytime after index k - 1, which is i - k + 1 >= 0. result.add(nums[deque.peekFirst()]); // since the deque is in decreasing order, and the max value is at the front of the deque } if(i - k + 1 == deque.peekFirst()){ // this is to remove the front element from the deque, if the front element happens to be the element where the slding window is leaving behind (this happens when the front element is the largest but since we are moving the sliding window so we have to remove this element from the sliding window and the deque as well) deque.pollFirst(); } } int[] res = new int[result.size()]; for(int m = 0; m < result.size(); m++){ // i can't be used again here, defined above already res[m] = result.get(m); } return res; } } Min from a fixed sliding window
239. Sliding Window Maximum/ min
猜你喜欢
转载自www.cnblogs.com/tobeabetterpig/p/9450834.html
今日推荐
周排行