File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments