Skip to content

Commit 9c4deff

Browse files
author
Yi Gu
committed
[Array] add Solution to Sliding Window Maximum
1 parent e2b634d commit 9c4deff

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Array/SlidingWindowMaximum.swift

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/sliding-window-maximum/
3+
* Primary idea: Use an array to store indices of elements, from larger to smaller,
4+
* adjust it while iterating the array
5+
*
6+
* Time Complexity: O(n), Space Complexity: O(n)
7+
*
8+
*/
9+
10+
class SlidingWindowMaximum {
11+
func maxSlidingWindow(nums: [Int], _ k: Int) -> [Int] {
12+
var maxIdx = [Int]()
13+
var res = [Int]()
14+
15+
for i in 0 ..< nums.count {
16+
while maxIdx.count > 0 && nums[maxIdx.last!] < nums[i] {
17+
maxIdx.removeLast()
18+
}
19+
20+
maxIdx.append(i)
21+
22+
if i + 1 >= k {
23+
res.append(nums[maxIdx.first!])
24+
}
25+
if i - maxIdx.first! + 1 == k {
26+
maxIdx.removeFirst()
27+
}
28+
}
29+
30+
return res
31+
}
32+
}

0 commit comments

Comments
 (0)