diff --git a/README.md b/README.md index 57ecc1e6..f44fc0a7 100644 --- a/README.md +++ b/README.md @@ -491,3 +491,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/). | 61. Rotate List | [Link](https://leetcode.com/problems/rotate-list/) | [Link](./lib/medium/61_rotate_list.rb) | | 62. Unique Paths | [Link](https://leetcode.com/problems/unique-paths/) | [Link](./lib/medium/62_unique_paths.rb) | | 71. Simplify Path | [Link](https://leetcode.com/problems/simplify-path/) | [Link](./lib/medium/71_simplify_path.rb) | +| 74. Search a 2D Matrix | [Link](https://leetcode.com/problems/search-a-2d-matrix/) | [Link](./lib/medium/74_search_a_2d_matrix.rb) | diff --git a/leetcode-ruby.gemspec b/leetcode-ruby.gemspec index 26782164..06bf0b07 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.2.5' + s.version = '6.2.6' s.license = 'MIT' s.files = ::Dir['lib/**/*.rb'] + %w[README.md] s.executable = 'leetcode-ruby' diff --git a/lib/medium/74_search_a_2d_matrix.rb b/lib/medium/74_search_a_2d_matrix.rb new file mode 100644 index 00000000..d39e5521 --- /dev/null +++ b/lib/medium/74_search_a_2d_matrix.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +# https://leetcode.com/problems/search-a-2d-matrix/ +# @param {Integer[][]} matrix +# @param {Integer} target +# @return {Boolean} +def search_matrix(matrix, target) + i = 0 + j = matrix.first.length - 1 + + while i < matrix.length && j >= 0 + curr = matrix[i][j] + + return true if curr == target + + i += 1 if curr < target + j -= 1 if curr > target + end + + false +end diff --git a/test/medium/test_74_search_a_2d_matrix.rb b/test/medium/test_74_search_a_2d_matrix.rb new file mode 100644 index 00000000..5cec1a81 --- /dev/null +++ b/test/medium/test_74_search_a_2d_matrix.rb @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +require_relative '../test_helper' +require_relative '../../lib/medium/74_search_a_2d_matrix' +require 'minitest/autorun' + +class SearchA2DMatrixTest < ::Minitest::Test + def test_default + assert(search_matrix([[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], 3)) + assert(!search_matrix([[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], 13)) + end +end