Skip to content

Commit 24e3e29

Browse files
authored
Merge pull request #709 from fartem/128_Longest_Consecutive_Sequence
2024-08-14 v. 6.4.7: added "128. Longest Consecutive Sequence"
2 parents 44b06d4 + 2882963 commit 24e3e29

File tree

4 files changed

+39
-1
lines changed

4 files changed

+39
-1
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,3 +512,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
512512
| 116. Populating Next Right Pointers in Each Node | [Link](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) | [Link](./lib/medium/116_populating_next_right_pointers_in_each_node.rb) |
513513
| 117. Populating Next Right Pointers in Each Node II | [Link](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/) | [Link](./lib/medium/117_populating_next_right_pointers_in_each_node_ii.rb) |
514514
| 120. Triangle | [Link](https://leetcode.com/problems/triangle/) | [Link](./lib/medium/120_triangle.rb) |
515+
| 128. Longest Consecutive Sequence | [Link](https://leetcode.com/problems/longest-consecutive-sequence/) | [Link](./lib/medium/128_longest_consecutive_sequence.rb) |

leetcode-ruby.gemspec

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ require 'English'
55
::Gem::Specification.new do |s|
66
s.required_ruby_version = '>= 3.0'
77
s.name = 'leetcode-ruby'
8-
s.version = '6.4.6'
8+
s.version = '6.4.7'
99
s.license = 'MIT'
1010
s.files = ::Dir['lib/**/*.rb'] + %w[README.md]
1111
s.executable = 'leetcode-ruby'
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# frozen_string_literal: true
2+
3+
require 'set'
4+
5+
# https://leetcode.com/problems/longest-consecutive-sequence/
6+
# @param {Integer[]} nums
7+
# @return {Integer}
8+
def longest_consecutive(nums)
9+
uniq = nums.to_set
10+
result = 0
11+
uniq.each do |num|
12+
next if uniq.include?(num - 1)
13+
14+
curr = num
15+
count = 1
16+
while uniq.include?(curr + 1)
17+
curr += 1
18+
count += 1
19+
end
20+
21+
result = [result, count].max
22+
end
23+
24+
result
25+
end
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# frozen_string_literal: true
2+
3+
require_relative '../test_helper'
4+
require_relative '../../lib/medium/128_longest_consecutive_sequence'
5+
require 'minitest/autorun'
6+
7+
class LongestConsequtiveSequenceTest < ::Minitest::Test
8+
def test_default
9+
assert_equal(4, longest_consecutive([100, 4, 200, 1, 3, 2]))
10+
assert_equal(9, longest_consecutive([0, 3, 7, 2, 5, 8, 4, 6, 0, 1]))
11+
end
12+
end

0 commit comments

Comments
 (0)