1. 滑动窗口的最大值
给定一个数组 nums 和滑动窗口的大小 k,请找出所有滑动窗口里的最大值。
示例:
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
解释:
滑动窗口的位置 最大值
--------------- -----
[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
- 大根堆
public ArrayList<Integer> maxInWindows(int [] num, int size) {
ArrayList<Integer> list = new ArrayList<>();
if (num == null || num.length == 0 || size < 1) return list;
PriorityQueue<Integer> queue = new PriorityQueue<>((t1, t2) -> t2 - t1);
for (int i = 0; i < num.length; i++) {
// 左边界
int j = i + 1 - size;
queue.offer(num[i]);
// 左边滑出
if (j > 0 && num[j - 1] == queue.peek()) {
queue.poll();
}
// 左边界
if (j >= 0) list.add(queue.peek());
}
return list;
}
- 记录最大项的位置
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size) {
ArrayList<Integer> list = new ArrayList<>();
if (num == null || num.length == 0 || size < 1) return list;
int maxIndex = -1, max = Integer.MIN_VALUE;;
for (int i = 0; i < num.length; i++) {
// 左边界
int j = i + 1 - size;
if (num[i] >= max) {
max = num[i];
maxIndex = i;
}
// 左边滑出
if (maxIndex < j) {
maxIndex = findMax(num, j, i);
max = num[maxIndex];
}
// 左边界
if (j >= 0) list.add(max);
}
return list;
}
private int findMax(int[] num, int i, int j) {
int index = i;
int max = num[i];
for (int k = i; k < j; k++) {
if (num[k] >= max) {
index = k;
max = num[k];
}
}
return index;
}
}
2.队列的最大值
请定义一个队列并实现函数 max_value 得到队列里的最大值,要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。
若队列为空,pop_front 和 max_value 需要返回 -1
输入:
["MaxQueue","push_back","push_back","max_value","pop_front","max_value"]
[[],[1],[2],[],[],[]]
输出: [null,null,null,2,1,2]
class MaxQueue {
private int maxValue = Integer.MIN_VALUE;
private LinkedList<Integer> queue;
public MaxQueue() {
queue = new LinkedList<>();
}
public int max_value() {
if (queue.size() == 0) return -1;
return maxValue;
}
public void push_back(int value) {
queue.addLast(value);
if (value > maxValue) {
maxValue = value;
}
}
public int pop_front() {
if (queue.size() == 0) return -1;
int first = queue.removeFirst();
if (queue.size() == 0) {
maxValue = Integer.MIN_VALUE;
return first;
}
if (first == maxValue) {
maxValue = Integer.MIN_VALUE;
Iterator<Integer> i = queue.iterator();
while(i.hasNext()) {
int tmp = i.next();
if (maxValue < tmp) {
maxValue = tmp;
}
}
}
return first;
}
}
/**
* Your MaxQueue object will be instantiated and called as such:
* MaxQueue obj = new MaxQueue();
* int param_1 = obj.max_value();
* obj.push_back(value);
* int param_3 = obj.pop_front();
*/
网友评论