Skip to content

Commit 1b1b526

Browse files
authored
feat: add swift implementation to lcof2 problem: No.119 (doocs#3712)
1 parent be68c1f commit 1b1b526

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,34 @@ var longestConsecutive = function (nums) {
221221
};
222222
```
223223

224+
#### Swift
225+
226+
```swift
227+
class Solution {
228+
func longestConsecutive(_ nums: [Int]) -> Int {
229+
let n = nums.count
230+
if n < 2 {
231+
return n
232+
}
233+
234+
let sortedNums = Array(Set(nums)).sorted()
235+
var ans = 1
236+
var currentStreak = 1
237+
238+
for i in 1..<sortedNums.count {
239+
if sortedNums[i] == sortedNums[i - 1] + 1 {
240+
currentStreak += 1
241+
ans = max(ans, currentStreak)
242+
} else {
243+
currentStreak = 1
244+
}
245+
}
246+
247+
return ans
248+
}
249+
}
250+
```
251+
224252
<!-- tabs:end -->
225253

226254
<!-- solution:end -->
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
func longestConsecutive(_ nums: [Int]) -> Int {
3+
let n = nums.count
4+
if n < 2 {
5+
return n
6+
}
7+
8+
let sortedNums = Array(Set(nums)).sorted()
9+
var ans = 1
10+
var currentStreak = 1
11+
12+
for i in 1..<sortedNums.count {
13+
if sortedNums[i] == sortedNums[i - 1] + 1 {
14+
currentStreak += 1
15+
ans = max(ans, currentStreak)
16+
} else {
17+
currentStreak = 1
18+
}
19+
}
20+
21+
return ans
22+
}
23+
}

0 commit comments

Comments
 (0)