Skip to content

Commit 3bba305

Browse files
authored
feat: add swift solution 2 implementation to lcof2 problem: No.119 (doocs#3713)
1 parent 1b1b526 commit 3bba305

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lcof2/剑指 Offer II 119. 最长连续序列/README.md

+27
Original file line numberDiff line numberDiff line change
@@ -388,6 +388,33 @@ var longestConsecutive = function (nums) {
388388
};
389389
```
390390

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+
391418
<!-- tabs:end -->
392419

393420
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}

0 commit comments

Comments
 (0)