Skip to content

Commit c7758de

Browse files
authored
feat: add swift implementation to lcof problem: No.59.2 (#2951)
1 parent 70dab83 commit c7758de

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

lcof/面试题59 - II. 队列的最大值/README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,49 @@ public class MaxQueue {
422422
*/
423423
```
424424

425+
#### Swift
426+
427+
```swift
428+
class MaxQueue {
429+
private var q1: [Int] = []
430+
private var q2: [Int] = []
431+
432+
init() {
433+
}
434+
435+
func max_value() -> Int {
436+
return q2.isEmpty ? -1 : q2.first!
437+
}
438+
439+
func push_back(_ value: Int) {
440+
q1.append(value)
441+
while !q2.isEmpty && q2.last! < value {
442+
q2.removeLast()
443+
}
444+
q2.append(value)
445+
}
446+
447+
func pop_front() -> Int {
448+
if q1.isEmpty {
449+
return -1
450+
}
451+
let ans = q1.removeFirst()
452+
if q2.first == ans {
453+
q2.removeFirst()
454+
}
455+
return ans
456+
}
457+
}
458+
459+
/**
460+
* Your MaxQueue object will be instantiated and called as such:
461+
* let obj = MaxQueue();
462+
* let param_1 = obj.max_value();
463+
* obj.push_back(value);
464+
* let param_3 = obj.pop_front();
465+
*/
466+
```
467+
425468
<!-- tabs:end -->
426469

427470
<!-- solution:end -->
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class MaxQueue {
2+
private var q1: [Int] = []
3+
private var q2: [Int] = []
4+
5+
init() {
6+
}
7+
8+
func max_value() -> Int {
9+
return q2.isEmpty ? -1 : q2.first!
10+
}
11+
12+
func push_back(_ value: Int) {
13+
q1.append(value)
14+
while !q2.isEmpty && q2.last! < value {
15+
q2.removeLast()
16+
}
17+
q2.append(value)
18+
}
19+
20+
func pop_front() -> Int {
21+
if q1.isEmpty {
22+
return -1
23+
}
24+
let ans = q1.removeFirst()
25+
if q2.first == ans {
26+
q2.removeFirst()
27+
}
28+
return ans
29+
}
30+
}

0 commit comments

Comments
 (0)