File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change @@ -422,6 +422,49 @@ public class MaxQueue {
422
422
*/
423
423
```
424
424
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
+
425
468
<!-- tabs:end -->
426
469
427
470
<!-- solution:end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments