forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Array] add solution to Longest Consecutive Sequence
- Loading branch information
Yi Gu
committed
Aug 7, 2016
1 parent
49bb6e0
commit 3aa0f0e
Showing
1 changed file
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/longest-consecutive-sequence/ | ||
* Primary idea: Iterate the array and check all neighbor numbers with the help of two sets | ||
* | ||
* Time Complexity: O(n), Space Complexity: O(n) | ||
* | ||
*/ | ||
|
||
class LongestConsecutiveSequence { | ||
func longestConsecutive(nums: [Int]) -> Int { | ||
guard nums.count > 0 else { | ||
return 0 | ||
} | ||
|
||
var setNums = Set<Int>(nums) | ||
var setDups = Set<Int>() | ||
var longest = 1 | ||
|
||
for num in nums { | ||
guard !setDups.contains(num) else { | ||
continue | ||
} | ||
|
||
setDups.insert(num) | ||
var len = 1 | ||
|
||
len += _helper(&setDups, &setNums, num, 1); | ||
len += _helper(&setDups, &setNums, num, -1); | ||
|
||
if (len > longest) { | ||
longest = len; | ||
} | ||
} | ||
|
||
return longest | ||
} | ||
|
||
private func _helper(inout setDups: Set<Int>, inout _ setNums: Set<Int>, _ num: Int, _ step: Int) -> Int { | ||
var len = 0 | ||
var num = num | ||
|
||
while setNums.contains(num + step) { | ||
num += step | ||
setDups.insert(num) | ||
len += 1 | ||
} | ||
|
||
return len | ||
} | ||
} |