File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
lcof2/剑指 Offer II 119. 最长连续序列 Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change @@ -221,6 +221,34 @@ var longestConsecutive = function (nums) {
221
221
};
222
222
```
223
223
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
+
224
252
<!-- tabs: end -->
225
253
226
254
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments