File tree Expand file tree Collapse file tree 1 file changed +11
-49
lines changed Expand file tree Collapse file tree 1 file changed +11
-49
lines changed Original file line number Diff line number Diff line change 1
1
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
48
13
end
49
- end
50
-
51
- hash . max_by { |_k , v | v } [ 1 ]
52
14
end
You can’t perform that action at this time.
0 commit comments