滑动窗口的最大值

滑动窗口的最大值

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

  1. 暴力解法:
import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] a, int size) {
        ArrayList<Integer> ret = new ArrayList<>();
        if (a == null || size > a.length || size == 0) {
            return ret;
        }
        for (int i = 0, j = size - 1; j < a.length; ++i, ++j) {
            int max = max(a, i, j);
            ret.add(max);
        }
        return ret;
    }

    private int max(int[] a, int l, int r) {
        int max = Integer.MIN_VALUE;
        for (int i = l; i <= r; ++i) {
            if (a[i] > max) {
                max = a[i];
            }
        }
        return max;
    }
}
  1. 大顶堆解法
import java.util.*;
public class Solution {
    private PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> b.compareTo(a)); // 大顶堆

    public ArrayList<Integer> maxInWindows(int [] a, int size) {
        ArrayList<Integer> ret = new ArrayList<>();
        if (a == null || size > a.length || size == 0) {
            return ret;
        }
        for (int i = 0, j = size - 1; j < a.length; ++i, ++j) {
            if (i == 0) {
                for (int k = i; k <=j; ++k) {
                    heap.offer(a[k]);
                }
            } else {
                heap.remove(a[i - 1]);
                heap.offer(a[j]);
            }
            int max = heap.peek();
            ret.add(max);
        }
        return ret;
    }
}
  1. 单调队列解法
import java.util.*;
public class Solution {
    public ArrayList<Integer> maxInWindows(int [] a, int size) {
        ArrayList<Integer> ret = new ArrayList<>();
        if (a == null || size > a.length || size == 0) {
            return ret;
        }

        Deque<Integer> dq = new LinkedList<>(); // dq里面存的是下标
        for (int i = 0; i < a.length; ++i) {
            while (!dq.isEmpty() && a[dq.peekLast()] < a[i]) {
                // 单调递减队列
                dq.pollLast();
            }
            dq.offerLast(i);
            if (dq.peekFirst() + size <= i) {
                // i代表了窗口的右端,此时已经越过了队列头的值
                dq.pollFirst();
            }
            if (i + 1 >= size) {
                // 说明已经可以形成窗口
                ret.add(a[dq.peekFirst()]);
            }
        }
        return ret;
    }
}
全部评论

相关推荐

黑皮白袜臭脚体育生:简历统一按使用了什么技术实现了什么功能解决了什么问题或提升了什么性能指标来写会更好另外宣传下自己的开源仿b站微服务项目,GitHub已经410star,牛客上有完整文档教程,如果觉得有帮助的话可以点个小星星,蟹蟹
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务