diff --git a/README.md b/README.md index 1db69c7f..234a9302 100644 --- a/README.md +++ b/README.md @@ -623,3 +623,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/). | 784. Letter Case Permutation | [Link](https://leetcode.com/problems/letter-case-permutation/) | [Link](./lib/medium/784_letter_case_permutation.rb) | [Link](./test/medium/test_784_letter_case_permutation.rb) | | 797. All Paths From Source to Target | [Link](https://leetcode.com/problems/all-paths-from-source-to-target/) | [Link](./lib/medium/797_all_paths_from_source_to_target.rb) | [Link](./test/medium/test_797_all_paths_from_source_to_target.rb) | | 814. Binary Tree Pruning | [Link](https://leetcode.com/problems/binary-tree-pruning/) | [Link](./lib/medium/814_binary_tree_pruning.rb) | [Link](./test/medium/test_814_binary_tree_pruning.rb) | +| 817. Linked List Components | [Link](https://leetcode.com/problems/linked-list-components/) | [Link](./lib/medium/817_linked_list_components.rb) | [Link](./test/medium/test_817_linked_list_components.rb) | diff --git a/leetcode-ruby.gemspec b/leetcode-ruby.gemspec index 6d947726..3c1a6c85 100644 --- a/leetcode-ruby.gemspec +++ b/leetcode-ruby.gemspec @@ -5,7 +5,7 @@ require 'English' ::Gem::Specification.new do |s| s.required_ruby_version = '>= 3.0' s.name = 'leetcode-ruby' - s.version = '7.5.8' + s.version = '7.5.9' s.license = 'MIT' s.files = ::Dir['lib/**/*.rb'] + %w[README.md] s.executable = 'leetcode-ruby' diff --git a/lib/medium/817_linked_list_components.rb b/lib/medium/817_linked_list_components.rb new file mode 100644 index 00000000..c193c71f --- /dev/null +++ b/lib/medium/817_linked_list_components.rb @@ -0,0 +1,26 @@ +# frozen_string_literal: true + +# https://leetcode.com/problems/linked-list-components/ +# @param {ListNode} head +# @param {Integer[]} nums +# @return {Integer} +def num_components(head, nums) + values = nums.to_set + result = 0 + is_connected = false + + while head + if values.include?(head.val) + unless is_connected + is_connected = true + result += 1 + end + else + is_connected = false + end + + head = head.next + end + + result +end diff --git a/test/medium/test_817_linked_list_components.rb b/test/medium/test_817_linked_list_components.rb new file mode 100644 index 00000000..50547aaa --- /dev/null +++ b/test/medium/test_817_linked_list_components.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require_relative '../test_helper' +require_relative '../../lib/common/linked_list' +require_relative '../../lib/medium/817_linked_list_components' +require 'minitest/autorun' + +class LinkedListComponentsTest < ::Minitest::Test + def test_default_one + assert_equal( + 2, + num_components( + ::ListNode.from_array( + [0, 1, 2, 3] + ), + [0, 1, 3] + ) + ) + end + + def test_default_two + assert_equal( + 2, + num_components( + ::ListNode.from_array( + [0, 1, 2, 3, 4] + ), + [0, 3, 1, 4] + ) + ) + end +end