Skip to content

2024-07-23 v. 6.2.6: added "74. Search a 2D Matrix" #685

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) |
2 changes: 1 addition & 1 deletion leetcode-ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
21 changes: 21 additions & 0 deletions lib/medium/74_search_a_2d_matrix.rb
Original file line number Diff line number Diff line change
@@ -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
12 changes: 12 additions & 0 deletions test/medium/test_74_search_a_2d_matrix.rb
Original file line number Diff line number Diff line change
@@ -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
Loading