File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
lcof2/剑指 Offer II 119. 最长连续序列 Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change @@ -360,6 +360,33 @@ var longestConsecutive = function (nums) {
360
360
};
361
361
```
362
362
363
+ #### Swift
364
+
365
+ ``` swift
366
+ class Solution {
367
+ func longestConsecutive (_ nums : [Int ]) -> Int {
368
+ let numSet: Set <Int > = Set (nums)
369
+ var longestStreak = 0
370
+
371
+ for num in nums {
372
+ if ! numSet.contains (num - 1 ) {
373
+ var currentNum = num
374
+ var currentStreak = 1
375
+
376
+ while numSet.contains (currentNum + 1 ) {
377
+ currentNum += 1
378
+ currentStreak += 1
379
+ }
380
+
381
+ longestStreak = max (longestStreak, currentStreak)
382
+ }
383
+ }
384
+
385
+ return longestStreak
386
+ }
387
+ }
388
+ ```
389
+
363
390
<!-- tabs: end -->
364
391
365
392
<!-- 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