1、题目
参考书:程序员代码面试指南 IT名企算法与数据结构题目最优解
2、解答
3、代码
public class 生成窗口最大值数组 {
public static int[] getMaxWindow(int[] arr, int w) {
if (arr.length < w || arr == null || w < 0) {
return null;
}
if (w == 1) {
return arr;
}
LinkedList<Integer> qmax = new LinkedList<>();
int[] res = new int[arr.length - w + 1];
int index = 0;
/**
* 1、如果qmax为空,i存入qmax
* 2、如果qmax不为空,取qmax队尾存放的下标,记为j
* 2.1、如果arr[j]>arr[i],把i存到队尾;
* 2.2、如果arr[j]<=arr[i],把j从qmax弹出。
*/
for (int i = 0; i < arr.length; i++) {
while (!qmax.isEmpty() && arr[qmax.peekLast()] <= arr[i]) {
qmax.pollLast();//检索并移除此列表的最后一个元素,或者如果此列表为空,则返回null。
}
qmax.addLast(i);//将指定元素追加在此列表的末尾。
/** 如果对头下标 == i-w 说明队头下标已过期 **/
if (qmax.peekFirst() == i - w) {//检索但不删除此列表的第一个元素,如果此列表为空,则返回null。
qmax.pollFirst();//检索并移除此列表的第一个元素,或者如果此列表为空,则返回null。
}
if (i >= w - 1) {//i>2
res[index] = arr[qmax.peekFirst()];
index++;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {4, 3, 5, 4, 3, 3, 6, 7};
int w = 3;
int[] res = getMaxWindow(arr, w);
for (Integer r : res) {
System.out.print(r + " ");
}
System.out.println();
test(arr);
}
/**
* public E peek():检索但不删除此列表的头部(第一个元素)。
* public E peekFirst():检索但不删除此列表的第一个元素,如果此列表为空,则返回null。
* public E peekLast():检索但不删除此列表的最后一个元素,如果此列表为空,则返回null。
*/
public static void test(int[] arr) {
LinkedList<Integer> qmax = new LinkedList<>();
for (Integer r : arr) {
qmax.add(r);
}
for (int i = 0; i < 10; i++) {
System.out.print(qmax.peekFirst() + " ");
System.out.print(qmax.peekLast() + " ");
}
}
}