diff --git a/README.md b/README.md index 6988954..ec7d66b 100644 --- a/README.md +++ b/README.md @@ -526,3 +526,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/). | 151. Reverse Words in a String | [Link](https://leetcode.com/problems/reverse-words-in-a-string/) | [Link](./lib/medium/151_reverse_words_in_a_string.rb) | [Link](./test/medium/test_151_reverse_words_in_a_string.rb) | | 155. Min Stack | [Link](https://leetcode.com/problems/min-stack/) | [Link](./lib/medium/155_min_stack.rb) | [Link](./test/medium/test_155_min_stack.rb) | | 165. Compare Version Numbers | [Link](https://leetcode.com/problems/compare-version-numbers/) | [Link](./lib/medium/165_compare_version_numbers.rb) | [Link](./test/medium/test_165_compare_version_numbers.rb) | +| 167. Two Sum II - Input Array Is Sorted | [Link](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) | [Link](./lib/medium/167_two_sum_ii_input_array_is_sorted.rb) | [Link](./test/medium/test_167_two_sum_ii_input_array_is_sorted.rb) | diff --git a/leetcode-ruby.gemspec b/leetcode-ruby.gemspec index 570de6c..0e78c0e 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 = '6.6.0' + s.version = '6.6.1' s.license = 'MIT' s.files = ::Dir['lib/**/*.rb'] + %w[README.md] s.executable = 'leetcode-ruby' diff --git a/lib/medium/167_two_sum_ii_input_array_is_sorted.rb b/lib/medium/167_two_sum_ii_input_array_is_sorted.rb new file mode 100644 index 0000000..e0bb0d8 --- /dev/null +++ b/lib/medium/167_two_sum_ii_input_array_is_sorted.rb @@ -0,0 +1,23 @@ +# frozen_string_literal: true + +# https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ +# @param {Integer[]} numbers +# @param {Integer} target +# @return {Integer[]} +def two_sum167(numbers, target) + start = 0 + nd = numbers.size - 1 + until start == nd + sum = numbers[start] + numbers[nd] + + if sum > target + nd -= 1 + elsif sum < target + start += 1 + else + break + end + end + + [start + 1, nd + 1] +end diff --git a/test/medium/test_167_two_sum_ii_input_array_is_sorted.rb b/test/medium/test_167_two_sum_ii_input_array_is_sorted.rb new file mode 100644 index 0000000..f83ad22 --- /dev/null +++ b/test/medium/test_167_two_sum_ii_input_array_is_sorted.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require_relative '../test_helper' +require_relative '../../lib/medium/167_two_sum_ii_input_array_is_sorted' +require 'minitest/autorun' + +class TwoSumIIInputArrayIsSortedTest < ::Minitest::Test + def test_default_one + assert_equal( + [1, 2], + two_sum167( + [2, 7, 11, 15], + 9 + ) + ) + end + + def test_default_two + assert_equal( + [1, 3], + two_sum167( + [2, 3, 4], + 6 + ) + ) + end + + def test_default_three + assert_equal( + [1, 2], + two_sum167( + [-1, 0], + -1 + ) + ) + end + + def test_additional_one + assert_equal( + [2, 3], + two_sum167( + [5, 25, 75], + 100 + ) + ) + end +end