题解 | 滑动窗口的最大值

滑动窗口的最大值

https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param num int整型一维数组
     * @param size int整型
     * @return int整型ArrayList
     */
    public ArrayList<Integer> maxInWindows (int[] num, int size) {
        // write code here

        ArrayList<Integer> result = new ArrayList<Integer>();
        if (size == 0) return result;
        if (size > num.length) return result;


        LinkedList<Integer> queue = new LinkedList<Integer>();
        for (int i = 0; i < num.length; i++) {
            if (queue.size() < size) {
                queue.offer(num[i]);
            } else {
                int max = getMaxLinked(queue, size);
                result.add(max);
                queue.pop();
                queue.offer(num[i]);
            }

        }

        int max1 = getMaxLinked(queue, size);
        result.add(max1);

        return result;
    }

    public int getMaxLinked(LinkedList<Integer> linkedList, int size) {
        int max = Integer.MIN_VALUE;
        int count = 0;
        while (!linkedList.isEmpty()) {
            if (count == size) break;
            int val = linkedList.poll();
            linkedList.offer(val);

            if (val > max) {
                max = val;
            }

            count++;
        }
        return max;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务