代码一
public class Solution {
public ArrayList<Integer> maxInWindows(int [] num, int size){
ArrayList<Integer> list = new ArrayList<Integer> ();
if(size>num.length||size==0)
return list;
for(int i = 0;i<=num.length-size;i++){
int max = num;
for(int j = i+1;j<i+size;j++){
if(num[j]>max){
max = num[j];
}
}
list.add(max);
}
return list;
}
}
代码二(借鉴)
public class Solution1 {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> ret = new ArrayList<>();
if (num == null) {
return ret;
}
if (num.length < size || size < 1) {
return ret;
}
LinkedList<Integer> indexDeque = new LinkedList<>();
for (int i = 0; i < size - 1; i++) {
while (!indexDeque.isEmpty() && num > num[indexDeque.getLast()]) {
indexDeque.removeLast();
}
indexDeque.addLast(i);
}
for (int i = size - 1; i < num.length; i++) {
while (!indexDeque.isEmpty() && num > num[indexDeque.getLast()]) {
indexDeque.removeLast();
}
indexDeque.addLast(i);
if (i - indexDeque.getFirst() + 1 > size) {
indexDeque.removeFirst();
}
ret.add(num[indexDeque.getFirst()]);
}
return ret;
}
}
public class Solution2 {
public ArrayList<Integer> maxInWindows(int [] num, int size)
{
ArrayList<Integer> res = new ArrayList<>();
if(size == 0) return res;
int begin;
ArrayDeque<Integer> q = new ArrayDeque<>();
for(int i = 0; i < num.length; i++){
begin = i - size + 1;
if(q.isEmpty())
q.add(i);
else if(begin > q.peekFirst())
q.pollFirst();