/*
* 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
* 例如,如果输入数组{2,3,4,2,6,2,5,1},大小是3;
* 滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1},
* {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1},
* {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。
*/
import java.util.*;
public class MaxInWindows {
//法一:借助辅助数组,然后排序找出最大值
public ArrayList<Integer> maxInWindows(int [] num, int size) {
ArrayList<Integer> list = new ArrayList<Integer>();
if(size <= 0 || num.length <= 0) return list;
int[] temp = new int[size];
for(int i = 0;i <= num.length - size;i ++) {
int j = i;
int count = 0; //计数器
while(count < size) {
temp[count ++] = num[j ++];
}
Arrays.sort(temp);
list.add(temp[temp.length - 1]);
}
return list;
}
//法二:借助双向队列(循环链表)
public ArrayList<Integer> maxInWindows2(int [] num, int size) {
ArrayList<Integer> arr = new ArrayList<Integer>();
if (num == null || size <= 0 || num.length < size)
return arr;
Deque<Integer> queue = new LinkedList<>();
for (int i = 0;i < num.length;i ++){
while(!queue.isEmpty() && num[i] >= num[queue.getLast()]) //下一个元素大于队尾元素,则移除队尾元素
queue.pollLast();
while(!queue.isEmpty() && queue.getFirst() < i - size + 1) // 队首元素不在滑动窗范围内,则移除队首元素
queue.pollFirst();
queue.offerLast(i); //将元素添加到队尾
if(i + 1 >= size) //下一个元素超过滑动窗的范围,则取出滑动窗元素的最大值(队首元素)
arr.add(num[queue.getFirst()]);
}
return arr;
}
public static void main(String[] args) {
int[] num = {2,3,4,2,6,2,5,1};
ArrayList<Integer> list = new MaxInWindows().maxInWindows2(num, 3);
for(int i : list) {
System.out.print(i + " ");
}
}
}
《剑指offer》-找出数组中所有滑动窗口里数值的最大值
最新推荐文章于 2022-04-30 18:02:31 发布