File tree 2 files changed +49
-0
lines changed
lcof2/剑指 Offer II 119. 最长连续序列
2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -388,6 +388,33 @@ var longestConsecutive = function (nums) {
388
388
};
389
389
```
390
390
391
+ #### Swift
392
+
393
+ ``` swift
394
+ class Solution {
395
+ func longestConsecutive (_ nums : [Int ]) -> Int {
396
+ let numSet: Set <Int > = Set (nums)
397
+ var longestStreak = 0
398
+
399
+ for num in nums {
400
+ if ! numSet.contains (num - 1 ) {
401
+ var currentNum = num
402
+ var currentStreak = 1
403
+
404
+ while numSet.contains (currentNum + 1 ) {
405
+ currentNum += 1
406
+ currentStreak += 1
407
+ }
408
+
409
+ longestStreak = max (longestStreak, currentStreak)
410
+ }
411
+ }
412
+
413
+ return longestStreak
414
+ }
415
+ }
416
+ ```
417
+
391
418
<!-- tabs: end -->
392
419
393
420
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func longestConsecutive( _ nums: [ Int ] ) -> Int {
3
+ let numSet : Set < Int > = Set ( nums)
4
+ var longestStreak = 0
5
+
6
+ for num in nums {
7
+ if !numSet. contains ( num - 1 ) {
8
+ var currentNum = num
9
+ var currentStreak = 1
10
+
11
+ while numSet. contains ( currentNum + 1 ) {
12
+ currentNum += 1
13
+ currentStreak += 1
14
+ }
15
+
16
+ longestStreak = max ( longestStreak, currentStreak)
17
+ }
18
+ }
19
+
20
+ return longestStreak
21
+ }
22
+ }
You can’t perform that action at this time.
0 commit comments