Skip to content

Commit 27ae84e

Browse files
committed
feat: add binary search
1 parent f3069e3 commit 27ae84e

File tree

5 files changed

+68
-0
lines changed

5 files changed

+68
-0
lines changed

Cargo.lock

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ members = [
33
"Array",
44
"DP",
55
"backtracking",
6+
"binary_search",
67
"compiler",
78
"sliding_window",
89
"String",

binary_search/Cargo.toml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
[package]
2+
name = "leetcode_binary_search"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
[lib]
8+
path = "lib.rs"
9+
doctest = false
10+
11+
[dependencies]

binary_search/_0704_binary_search.rs

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// https://leetcode.com/problems/binary-search
2+
//
3+
// Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`.
4+
//
5+
// You must write an algorithm with `O(log n)` runtime complexity.
6+
//
7+
// **Example 1:**
8+
//
9+
// ```
10+
// **Input:** nums = [-1,0,3,5,9,12], target = 9
11+
// **Output:** 4
12+
// **Explanation:** 9 exists in nums and its index is 4
13+
// ```
14+
//
15+
// **Example 2:**
16+
//
17+
// ```
18+
// **Input:** nums = [-1,0,3,5,9,12], target = 2
19+
// **Output:** -1
20+
// **Explanation:** 2 does not exist in nums so return -1
21+
// ```
22+
//
23+
// **Constraints:**
24+
//
25+
// * `1 <= nums.length <= 10<sup>4</sup>`
26+
// * `-10<sup>4</sup> < nums[i], target < 10<sup>4</sup>`
27+
// * All the integers in `nums` are **unique**.
28+
// * `nums` is sorted in ascending order.
29+
30+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
31+
let mut left = 0;
32+
let mut right = nums.len() as i32 - 1;
33+
while left <= right {
34+
let mid = (left + right) / 2;
35+
if nums[mid as usize] == target {
36+
return mid;
37+
} else if nums[mid as usize] < target {
38+
left = mid + 1;
39+
} else {
40+
right = mid - 1;
41+
}
42+
}
43+
return -1;
44+
}
45+
46+
#[test]
47+
pub fn t1() {
48+
assert_eq!(search(vec![-1,0,3,5,9,12], 9), 4);
49+
}

binary_search/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
#![allow(dead_code)]
2+
3+
mod _0704_binary_search;

0 commit comments

Comments
 (0)