File tree Expand file tree Collapse file tree 1 file changed +105
-0
lines changed Expand file tree Collapse file tree 1 file changed +105
-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
+ */
4
+
5
+ class SlidingWindowMaximum {
6
+ func maxSlidingWindow( _ nums: [ Int ] , _ k: Int ) -> [ Int ] {
7
+ var output = [ Int] ( )
8
+ var deque = Deque ( )
9
+ var l = 0
10
+ var r = 0
11
+
12
+ while r < nums. count {
13
+ while !deque. isEmpty && nums [ deque. last!] < nums [ r] {
14
+ deque. popRight ( )
15
+ }
16
+ deque. pushRight ( r)
17
+
18
+ if l > deque. first! {
19
+ deque. popLeft ( )
20
+ }
21
+
22
+ if ( r + 1 ) >= k {
23
+ output. append ( nums [ deque. first!] )
24
+ l += 1
25
+ }
26
+
27
+ r += 1
28
+ }
29
+
30
+ return output
31
+ }
32
+ }
33
+
34
+ struct Deque {
35
+ private var storage : [ Int ? ]
36
+ private var head : Int
37
+ private var capacity : Int
38
+ private let originalCapacity : Int
39
+
40
+ var isEmpty : Bool {
41
+ storage. count - head == 0
42
+ }
43
+
44
+ var first : Int ? {
45
+ if isEmpty {
46
+ return nil
47
+ } else {
48
+ return storage [ head]
49
+ }
50
+ }
51
+
52
+ var last : Int ? {
53
+ if isEmpty {
54
+ return nil
55
+ } else {
56
+ return storage. last!
57
+ }
58
+ }
59
+
60
+ init ( capacity: Int = 10 ) {
61
+ self . capacity = max ( capacity, 1 )
62
+ self . storage = [ Int? ] ( repeating: nil , count: capacity)
63
+ self . originalCapacity = self . capacity
64
+ self . head = capacity
65
+ }
66
+
67
+ mutating func pushLeft( _ value: Int ) {
68
+ if head == 0 {
69
+ capacity *= 2
70
+ let emptySpace = [ Int? ] ( repeating: nil , count: capacity)
71
+ storage. insert ( contentsOf: emptySpace, at: 0 )
72
+ head = capacity
73
+ }
74
+
75
+ head -= 1
76
+ storage [ head] = value
77
+ }
78
+
79
+ mutating func popLeft( ) {
80
+ guard
81
+ head < storage. count,
82
+ let value = storage [ head]
83
+ else {
84
+ return
85
+ }
86
+
87
+ storage [ head] = nil
88
+ head += 1
89
+
90
+ if capacity >= originalCapacity, head >= capacity * 2 {
91
+ let emptySpace = capacity + capacity / 2
92
+ storage. removeFirst ( emptySpace)
93
+ head -= emptySpace
94
+ capacity /= 2
95
+ }
96
+ }
97
+
98
+ mutating func pushRight( _ value: Int ) {
99
+ storage. append ( value)
100
+ }
101
+
102
+ mutating func popRight( ) {
103
+ storage. removeLast ( )
104
+ }
105
+ }
You can’t perform that action at this time.
0 commit comments