forked from neetcode-gh/leetcode
-
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.
Merge pull request neetcode-gh#2016 from MikeQCarr/longest-consecutiv…
…e-sequence Update: 0128-longest-consecutive-sequence.rb
- Loading branch information
Showing
1 changed file
with
11 additions
and
49 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 |
---|---|---|
@@ -1,52 +1,14 @@ | ||
def longest_consecutive(nums) | ||
return 0 if nums.empty? | ||
|
||
hash = {} | ||
nums.each { |num| hash[num] = true } | ||
longest = 0 | ||
nums.each do |num| | ||
next if hash[num - 1] | ||
|
||
challenger = 1 | ||
loop do | ||
if hash[num + challenger] | ||
challenger += 1 | ||
else | ||
break | ||
end | ||
end | ||
longest = challenger if challenger > longest | ||
end | ||
|
||
longest | ||
end | ||
|
||
# Another way to do it. | ||
def longest_consecutive(nums) | ||
return 0 if nums.empty? | ||
|
||
hash = {} | ||
nums.each { |num| hash[num] = -1 } | ||
nums.each do |num| | ||
next unless hash[num] == -1 | ||
|
||
longest_consec = 1 | ||
loop do | ||
val = hash[num + longest_consec] | ||
case val | ||
when -1 | ||
hash[num + longest_consec] = -2 | ||
longest_consec += 1 | ||
when nil | ||
hash[num] = longest_consec | ||
break | ||
else | ||
longest_consec += hash[num + longest_consec] | ||
hash[num] = longest_consec | ||
break | ||
end | ||
set = Set.new(nums) | ||
set.reduce(0) do |longest, num| | ||
if !set.include?(num-1) | ||
length = 0 | ||
while set.include?(num + length) do | ||
length += 1 | ||
end | ||
next(longest > length ? longest : length) | ||
end | ||
|
||
longest | ||
end | ||
end | ||
|
||
hash.max_by { |_k, v| v }[1] | ||
end |