鱼C论坛

 找回密码
 立即注册
查看: 1711|回复: 0

[学习笔记] leetcode 239. Sliding Window Maximum

[复制链接]
发表于 2019-9-30 08:41:47 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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. Return the max sliding window.

Example:

Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
Output: [3,3,5,5,6,7] 
Explanation: 

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
Note:
You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty array.

Follow up:
Could you solve it in linear time?
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        int i = 0, j;
        int n = nums.length;
        List <Integer> list = new ArrayList<>();
        List <Integer> max = new ArrayList<>();
        for(j = 0; j < n ; j++){
            max.add(nums[j]);
            
            if(j - i + 1>= k){
                list.add(Collections.max(max));
                max.remove(i);
            }
        }
        
        int[] ret = list.stream().mapToInt(x ->x).toArray();
        return ret;
    }
}
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums.length == 0 || k == 0) return nums;
        int j = 0, n = nums.length;
        int[] arr = new int[n-k+1];
        for(int i = 0; i< n ; i++){
            int max = Integer.MIN_VALUE;
            if(i - j +1 >= k){
                for(int m = j; m <= i; m++){
                    max = Math.max(max, nums[m]);
                }
                arr[i-k+1] = max;
                j++;
                
            }
        }
        
        return arr;
    }
}

monotonic queue!
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        if(nums.length == 0) return nums;
        int n = nums.length;
        int[] res = new int[n - k +1];
        ArrayDeque<Integer> index = new ArrayDeque<>();
        for(int i =0; i< n; i++){
            while(!index.isEmpty() && nums[i] > nums[index.peekLast()]){
                index.pollLast();
            }
            index.offerLast(i);
            if(i - k + 1 >= 0){
                res[i - k+1] = nums[index.peekFirst()];
            }
            if(i - k + 1>= index.peekFirst()) index.pop();
        }
        
        return res;
    }
}

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-23 10:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表