题目链接
You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Method 1
每个window分别找最大
Time complexity: n - k + 1 windows, take O(k) to find the largest element from each window
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int loop = nums.length - k;
int[] result = new int[loop+1];
int windowSize;
int index = 0;
for (int i = 0; i <= loop; i++){
windowSize = k;
int min = Integer.MIN_VALUE;
while (windowSize != 0){
min = Math.max(nums[index], min);
index++;
windowSize--;
}
index = i + 1;
result[i] = min;
}
return result;
}
}
Method 2
回忆deque Method
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *First Element (Head) | Last Element (Tail) | |||
---|---|---|---|---|
Throws exception | Special value | Throws exception | Special value | |
Insert | addFirst(e) | offerFirst(e) | addLast(e) | offerLast(e) |
Remove | removeFirst() | pollFirst() | removeLast() | pollLast() |
Examine | getFirst() | peekFirst() | getLast() | peekLast() |
{@code Queue} Method | Equivalent {@code Deque} Method |
---|---|
{@link #add(Object) add(e)} | {@link #addLast(Object) addLast(e)} |
{@link #offer(Object) offer(e)} | {@link #offerLast(Object) offerLast(e)} |
{@link #remove() remove()} | {@link #removeFirst() removeFirst()} |
{@link #poll() poll()} | {@link #pollFirst() pollFirst()} |
{@link #element() element()} | {@link #getFirst() getFirst()} |
{@link #peek() peek()} | {@link #peekFirst() peekFirst()} |
Stack Method | Equivalent {@code Deque} Method |
---|---|
{@link #push(Object) push(e)} | {@link #addFirst(Object) addFirst(e)} |
{@link #pop() pop()} | {@link #removeFirst() removeFirst()} |
{@link #peek() peek()} | {@link #getFirst() getFirst()} |
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
Deque<Integer> dq = new ArrayDeque<>();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < k; i++){
while(!dq.isEmpty() && nums[i] >= nums[dq.peekLast()]){
dq.pollLast();
}
dq.offerLast(i);
}
list.add(nums[dq.peekFirst()]);
for (int i = k; i < nums.length; i++){
if(dq.peekFirst() == i-k){
dq.pollFirst();
}
while (!dq.isEmpty() && nums[i] >= nums[dq.peekLast()]) {
dq.pollLast();
}
dq.offerLast(i);
list.add(nums[dq.peekFirst()]);
}
return list.stream().mapToInt(i->i).toArray();
}
}