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

153. Find Minimum in Rotated Sorted Array #2

Merged
merged 1 commit into from
Jun 16, 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 src/solutions.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod s_110_balanced_binary_tree;
mod s_143_reorder_list;
mod s_153_find_minimum_in_rotated_sorted_array;
mod s_155_min_stack;
mod s_198_house_robbers;
mod s_19_remove_nth_node_from_end_of_list;
Expand Down
39 changes: 39 additions & 0 deletions src/solutions/s_153_find_minimum_in_rotated_sorted_array.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
struct Solution {}

impl Solution {
pub fn find_min(nums: Vec<i32>) -> i32 {
let mut left_ptr = 0;
let mut right_ptr = nums.len() - 1;
while left_ptr <= right_ptr {
let mid_ptr = (left_ptr + right_ptr) / 2;
if nums[left_ptr] <= nums[mid_ptr] && nums[mid_ptr] <= nums[right_ptr] {
return nums[left_ptr];
}
if nums[left_ptr] <= nums[mid_ptr] {
left_ptr = mid_ptr + 1
} else {
right_ptr = mid_ptr
}
}
return -1;
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_multi_element() {
let input = vec![3, 4, 5, 1, 2];
let res = Solution::find_min(input);
assert_eq!(res, 1)
}

#[test]
fn test_single_element() {
let input = vec![1];
let res = Solution::find_min(input);
assert_eq!(res, 1)
}
}