Skip to content

Commit dac7dd6

Browse files
committed
704. Binary Search: AC
1 parent fd46522 commit dac7dd6

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/solution/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,3 +512,4 @@ mod s0699_falling_squares;
512512
mod s0700_search_in_a_binary_search_tree;
513513
mod s0701_insert_into_a_binary_search_tree;
514514
mod s0703_kth_largest_element_in_a_stream;
515+
mod s0704_binary_search;
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/**
2+
* [0704] Binary Search
3+
*
4+
* 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.
5+
* You must write an algorithm with O(log n) runtime complexity.
6+
*
7+
* Example 1:
8+
*
9+
* Input: nums = [-1,0,3,5,9,12], target = 9
10+
* Output: 4
11+
* Explanation: 9 exists in nums and its index is 4
12+
*
13+
* Example 2:
14+
*
15+
* Input: nums = [-1,0,3,5,9,12], target = 2
16+
* Output: -1
17+
* Explanation: 2 does not exist in nums so return -1
18+
*
19+
*
20+
* Constraints:
21+
*
22+
* 1 <= nums.length <= 10^4
23+
* -10^4 < nums[i], target < 10^4
24+
* All the integers in nums are unique.
25+
* nums is sorted in ascending order.
26+
*
27+
*/
28+
pub struct Solution {}
29+
30+
// problem: https://leetcode.com/problems/binary-search/
31+
// discuss: https://leetcode.com/problems/binary-search/discuss/?currentPage=1&orderBy=most_votes&query=
32+
33+
// submission codes start here
34+
35+
impl Solution {
36+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
37+
let (mut low, mut high) = (0, nums.len());
38+
while low < high {
39+
let mid = low + (high - low) / 2;
40+
match nums[mid].cmp(&target) {
41+
std::cmp::Ordering::Equal => return mid as i32,
42+
std::cmp::Ordering::Less => low = mid + 1,
43+
std::cmp::Ordering::Greater => high = mid,
44+
}
45+
}
46+
-1
47+
}
48+
}
49+
50+
// submission codes end
51+
52+
#[cfg(test)]
53+
mod tests {
54+
use super::*;
55+
56+
#[test]
57+
fn test_0704_example_1() {
58+
let nums = vec![-1, 0, 3, 5, 9, 12];
59+
let target = 9;
60+
let result = 4;
61+
62+
assert_eq!(Solution::search(nums, target), result);
63+
}
64+
65+
#[test]
66+
fn test_0704_example_2() {
67+
let nums = vec![-1, 0, 3, 5, 9, 12];
68+
let target = 2;
69+
let result = -1;
70+
71+
assert_eq!(Solution::search(nums, target), result);
72+
}
73+
}

0 commit comments

Comments
 (0)