Skip to content

Commit 3340ef1

Browse files
authored
Update 0128-longest-consecutive-sequence.rb
More concise solution that is similar to python solution demonstrated in youtube video.
1 parent a14fcbd commit 3340ef1

File tree

1 file changed

+11
-49
lines changed

1 file changed

+11
-49
lines changed
Lines changed: 11 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,14 @@
11
def longest_consecutive(nums)
2-
return 0 if nums.empty?
3-
4-
hash = {}
5-
nums.each { |num| hash[num] = true }
6-
longest = 0
7-
nums.each do |num|
8-
next if hash[num - 1]
9-
10-
challenger = 1
11-
loop do
12-
if hash[num + challenger]
13-
challenger += 1
14-
else
15-
break
16-
end
17-
end
18-
longest = challenger if challenger > longest
19-
end
20-
21-
longest
22-
end
23-
24-
# Another way to do it.
25-
def longest_consecutive(nums)
26-
return 0 if nums.empty?
27-
28-
hash = {}
29-
nums.each { |num| hash[num] = -1 }
30-
nums.each do |num|
31-
next unless hash[num] == -1
32-
33-
longest_consec = 1
34-
loop do
35-
val = hash[num + longest_consec]
36-
case val
37-
when -1
38-
hash[num + longest_consec] = -2
39-
longest_consec += 1
40-
when nil
41-
hash[num] = longest_consec
42-
break
43-
else
44-
longest_consec += hash[num + longest_consec]
45-
hash[num] = longest_consec
46-
break
47-
end
2+
set = Set.new(nums)
3+
set.reduce(0) do |longest, num|
4+
if !set.include?(num-1)
5+
length = 0
6+
while set.include?(num + length) do
7+
length += 1
8+
end
9+
next(longest > length ? longest : length)
10+
end
11+
12+
longest
4813
end
49-
end
50-
51-
hash.max_by { |_k, v| v }[1]
5214
end

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy