Skip to content
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

2023-08-02 v. 1.3.7: added "704. Binary Search" #187

Merged
merged 1 commit into from
Aug 2, 2023
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 @@ -142,3 +142,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
| 693. Binary Number with Alternating Bits | [Link](https://leetcode.com/problems/binary-number-with-alternating-bits/) | [Link](./lib/easy/693_binary_number_with_alternating_bits.rb) |
| 700. Search in a Binary Search Tree | [Link](https://leetcode.com/problems/search-in-a-binary-search-tree/) | [Link](./lib/easy/700_search_in_a_binary_search_tree.rb) |
| 703. Kth Largest Element in a Stream | [Link](https://leetcode.com/problems/kth-largest-element-in-a-stream/) | [Link](./lib/easy/703_kth_largest_element_in_a_stream.rb) |
| 704. Binary Search | [Link](https://leetcode.com/problems/binary-search/) | [Link](./lib/easy/704_binary_search.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 = '1.3.6.1'
s.version = '1.3.7'
s.license = 'MIT'
s.files = ::Dir['lib/**/*.rb'] + %w[bin/leetcode-ruby README.md LICENSE]
s.executable = 'leetcode-ruby'
Expand Down
24 changes: 24 additions & 0 deletions lib/easy/704_binary_search.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# frozen_string_literal: true

# https://leetcode.com/problems/binary-search/
# @param {Integer[]} nums
# @param {Integer} target
# @return {Integer}
def search(nums, target)
l = 0
r = nums.length - 1
while l <= r
m = l + (r - l) / 2
num = nums[m]

return m if num == target

if num < target
l = m + 1
else
r = m - 1
end
end

-1
end
12 changes: 12 additions & 0 deletions test/easy/test_704_binary_search.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/easy/704_binary_search'
require 'minitest/autorun'

class BinarySearchTest < ::Minitest::Test
def test_default
assert_equal(4, search([-1, 0, 3, 5, 9, 12], 9))
assert_equal(-1, search([-1, 0, 3, 5, 9, 12], 2))
end
end
Loading