Skip to content

Commit 1f39628

Browse files
committed
feat: add swift solution 2 implementation to lcof2 problem: No.119
1 parent 3b52bea commit 1f39628

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,33 @@ var longestConsecutive = function (nums) {
360360
};
361361
```
362362

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+
363390
<!-- tabs:end -->
364391

365392
<!-- solution:end -->
Lines changed: 22 additions & 0 deletions
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)