forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0239-sliding-window-maximum.swift
105 lines (87 loc) · 2.24 KB
/
0239-sliding-window-maximum.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/**
* Question Link: https://leetcode.com/problems/sliding-window-maximum/
*/
class SlidingWindowMaximum {
func maxSlidingWindow(_ nums: [Int], _ k: Int) -> [Int] {
var output = [Int]()
var deque = Deque()
var l = 0
var r = 0
while r < nums.count {
while !deque.isEmpty && nums[deque.last!] < nums[r] {
deque.popRight()
}
deque.pushRight(r)
if l > deque.first! {
deque.popLeft()
}
if (r + 1) >= k {
output.append(nums[deque.first!])
l += 1
}
r += 1
}
return output
}
}
struct Deque {
private var storage: [Int?]
private var head: Int
private var capacity: Int
private let originalCapacity: Int
var isEmpty: Bool {
storage.count - head == 0
}
var first: Int? {
if isEmpty {
return nil
} else {
return storage[head]
}
}
var last: Int? {
if isEmpty {
return nil
} else {
return storage.last!
}
}
init(capacity: Int = 10) {
self.capacity = max(capacity, 1)
self.storage = [Int?](repeating: nil, count: capacity)
self.originalCapacity = self.capacity
self.head = capacity
}
mutating func pushLeft(_ value: Int) {
if head == 0 {
capacity *= 2
let emptySpace = [Int?](repeating: nil, count: capacity)
storage.insert(contentsOf: emptySpace, at: 0)
head = capacity
}
head -= 1
storage[head] = value
}
mutating func popLeft() {
guard
head < storage.count,
let value = storage[head]
else {
return
}
storage[head] = nil
head += 1
if capacity >= originalCapacity, head >= capacity * 2 {
let emptySpace = capacity + capacity / 2
storage.removeFirst(emptySpace)
head -= emptySpace
capacity /= 2
}
}
mutating func pushRight(_ value: Int) {
storage.append(value)
}
mutating func popRight() {
storage.removeLast()
}
}