20240717 Finished

This commit is contained in:
jackfiled 2024-07-17 11:08:31 +08:00
parent 82cbf0c774
commit 99aeb194f3
2 changed files with 60 additions and 1 deletions

View File

@ -175,4 +175,5 @@ mod p108_convert_sorted_array_to_binary_search_tree;
mod p53_maximum_subarray; mod p53_maximum_subarray;
mod p918_maximum_sum_circular_subarray; mod p918_maximum_sum_circular_subarray;
mod p35_search_insert_position; mod p35_search_insert_position;
mod p74_search_a_2d_matrix; mod p74_search_a_2d_matrix;
mod p33_search_in_rotated_sorted_array;

View File

@ -0,0 +1,58 @@
/**
* [33] Search in Rotated Sorted Array
*/
pub struct Solution {}
// submission codes start here
impl Solution {
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
if nums.len() == 1 {
return if target == nums[0] {
0
} else {
-1
};
}
let (mut left, mut right) = (0, nums.len());
while left < right {
let middle = (right - left) / 2 + left;
if nums[middle] == target {
return middle as i32;
}
if nums[middle] > nums[0] {
// 左侧的数组是有序的
if target >= nums[0] && target < nums[middle] {
right = middle;
} else {
left = middle + 1;
}
} else {
// 右侧数组是有序的
if target > nums[middle] && target <= nums[nums.len() - 1] {
left = middle + 1;
} else {
right = middle;
}
}
}
-1
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_33() {
}
}