问题一
队列的最大值: https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/
思路:其实本题需要实现的是一个优先队列,可以用作第二题的解答。
class MaxQueue {
private List<Integer> list;
public MaxQueue() {
list = new LinkedList<>();
}
public int max_value() {
int maxVal = -1;
for (int i : list) {
if (i > maxVal) {
maxVal = i;
}
}
return maxVal;
}
public void push_back(int value) {
list.add(value);
}
public int pop_front() {
if (list.size() > 0) {
return list.remove(0);
}
return -1;
}
}
问题二
滑动窗口的最大值:https://leetcode-cn.com/problems/hua-dong-chuang-kou-de-zui-da-zhi-lcof/
思路:可以利用上题的结构来解决此题。也可以利用treeMap来实现,需要注意的是最大值可能有多个。还有一种比较好的思路是使用有线队列来实现。
思路一:使用TreeMap实现。
public int[] maxSlidingWindow(int[] nums, int k) {
if (nums.length == 0) {
return new int[]{0};
}
TreeMap<Integer, Integer> treeMap = new TreeMap<>(Comparator.naturalOrder());
int[] result = new int[nums.length - k + 1];
int firstNum = nums[0], lastNum, currentNum, times;
for (int i = 0; i < k; i++) {
currentNum = nums[i];
times = 1;
if (treeMap.containsKey(currentNum)) {
times = treeMap.get(currentNum) + 1;
}
treeMap.put(currentNum, times);
}
result[0] = treeMap.lastKey();
// 从第二个开始
for (int i = k; i < nums.length; i++) {
// 移除第一个数
times = treeMap.get(firstNum);
if (times > 1) {
treeMap.put(firstNum, times - 1);
} else {
treeMap.remove(firstNum);
}
// 重新设置最后一个数与第一个数
firstNum = nums[i - k + 1];
lastNum = nums[i];
// 放入最后一个数
times = 1;
if (treeMap.containsKey(lastNum)) {
times = treeMap.get(lastNum) + 1;
}
treeMap.put(lastNum, times);
result[i - k + 1] = treeMap.lastKey();
}
return result;
}
思路二:使用有线队列
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
public int compare(int[] pair1, int[] pair2) {
return pair1[0] != pair2[0] ? pair2[0] - pair1[0] : pair2[1] - pair1[1];
}
});
for (int i = 0; i < k; ++i) {
pq.offer(new int[]{nums[i], i});
}
int[] ans = new int[n - k + 1];
ans[0] = pq.peek()[0];
for (int i = k; i < n; ++i) {
pq.offer(new int[]{nums[i], i});
while (pq.peek()[1] <= i - k) {
pq.poll();
}
ans[i - k + 1] = pq.peek()[0];
}
return ans;
}