Skip to content

Commit 43e2df4

Browse files
committed
Refactor solution to Longest Consecutive Sequence
1 parent 47a56fb commit 43e2df4

File tree

1 file changed

+13
-15
lines changed

1 file changed

+13
-15
lines changed

Array/LongestConsecutiveSequence.swift

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,28 +8,26 @@
88

99
class LongestConsecutiveSequence {
1010
func longestConsecutive(_ nums: [Int]) -> Int {
11-
var set = Set(nums), longest = 0
11+
var set = Set<Int>(nums), longest = 0
1212

1313
for num in nums {
14-
if set.contains(num) {
15-
set.remove(num)
16-
let distance = 1 + findConsecutive(&set, num, 1) + findConsecutive(&set, num, -1)
17-
longest = max(longest, distance)
18-
}
19-
}
14+
var currentLength = 1
15+
dfs(num, &set, &longest, &currentLength)
16+
}
2017

2118
return longest
2219
}
2320

24-
fileprivate func findConsecutive(_ set: inout Set<Int>, _ num: Int, _ step: Int) -> Int {
25-
var len = 0, num = num + step
26-
27-
while set.contains(num) {
28-
set.remove(num)
29-
len += 1
30-
num += step
21+
private func dfs(_ num: Int, _ set: inout Set<Int>, _ longest: inout Int, _ length: inout Int) {
22+
if !set.contains(num) {
23+
return
3124
}
3225

33-
return len
26+
longest = max(longest, length)
27+
set.remove(num)
28+
length += 1
29+
30+
dfs(num + 1, &set, &longest, &length)
31+
dfs(num - 1, &set, &longest, &length)
3432
}
3533
}

0 commit comments

Comments
 (0)