⭐️⭐️⭐️⭐️⭐️
# 題目敘述
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.
Return the max sliding window.
# Example 1
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
Explanation:Window position Max --------------- ----- [1 3 -1] -3 5 3 6 7 3 1 [3 -1 -3] 5 3 6 7 3 1 3 [-1 -3 5] 3 6 7 5 1 3 -1 [-3 5 3] 6 7 5 1 3 -1 -3 [5 3 6] 7 6 1 3 -1 -3 5 [3 6 7] 7
# Example 2
Input: nums = [1], k = 1
Output: [1]
# 解題思路
- Use Deque name
dq
. - Map
k
integer in thenums
, and keep the high number in thedq
first value. - Adding
dp
first value inList
nameres
which will become the answer. - Making
List<Integer>
intoint[]
and return.
# Solution
import java.util.ArrayDeque; | |
import java.util.ArrayList; | |
import java.util.Deque; | |
import java.util.List; | |
class Solution { | |
public int[] maxSlidingWindow(int[] nums, int k) { | |
Deque<Integer> dq = new ArrayDeque<>(); | |
List<Integer> res = new ArrayList<>(); | |
for (int i = 0; i < k; i++) { | |
while (!dq.isEmpty() && nums[i] >= nums[dq.peekLast()]) { | |
dq.pollLast(); | |
} | |
dq.offerLast(i); | |
} | |
res.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); | |
res.add(nums[dq.peekFirst()]); | |
} | |
return res.stream().mapToInt(Integer::intValue).toArray(); | |
} | |
} |
單字
片語 & 搭配詞
make sth into sth
把… 變成 make + 受詞 (物) + into + 受詞 (物)
- They’ve made the spare room into an office.
他們已把空置的房間改成辦公室。