LeetCode--239--hard--SlidingWindowMaximum

package com.app.main.LeetCode.slidingwindow;

import java.util.ArrayList;
import java.util.List;

/**
 * 239
 *
 * hard
 *
 * https://leetcode.com/problems/sliding-window-maximum/
 *
 * 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?
 *
 * Accepted
 * 215,076
 * Submissions
 * 531,204
 *
 *
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2020/1/23
 * Time:下午2:39
 */
public class SlidingWindowMaximum {

    private List<Integer> ans = new ArrayList<>();
    public int[] maxSlidingWindow(int[] nums, int k) {

        if (nums.length == 0 || k == 0) {
            return new int[0];
        }
        int l = 0;
        int r = k - 1;
        while (r < nums.length) {
            process(nums, l, r);
            l++;
            r++;
        }
        int[] res= new int[ans.size()];
        for (int i = 0; i < ans.size(); i++) {
            res[i] = ans.get(i);
        }
        return res;
    }

    private void process(int[] nums, int l, int r) {
        int max = nums[l];
        for (int i = l + 1; i <= r; i++) {
            max = Math.max(max, nums[i]);
        }
        ans.add(max);
    }
}
发布了187 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/huangdingsheng/article/details/104306085
今日推荐