Skip to content

Commit 9947333

Browse files
committed
solve #153
1 parent 41caddb commit 9947333

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,3 +147,4 @@ mod n0149_max_points_on_a_line;
147147
mod n0150_evaluate_reverse_polish_notation;
148148
mod n0151_reverse_words_in_a_string;
149149
mod n0152_maximum_product_subarray;
150+
mod n0153_find_minimum_in_rotated_sorted_array;
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/**
2+
* [153] Find Minimum in Rotated Sorted Array
3+
*
4+
* Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
5+
*
6+
* (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
7+
*
8+
* Find the minimum element.
9+
*
10+
* You may assume no duplicate exists in the array.
11+
*
12+
* Example 1:
13+
*
14+
*
15+
* Input: [3,4,5,1,2]
16+
* Output: 1
17+
*
18+
*
19+
* Example 2:
20+
*
21+
*
22+
* Input: [4,5,6,7,0,1,2]
23+
* Output: 0
24+
*
25+
*
26+
*/
27+
pub struct Solution {}
28+
29+
// submission codes start here
30+
31+
impl Solution {
32+
pub fn find_min(nums: Vec<i32>) -> i32 {
33+
let mut size = nums.len();
34+
if size == 0 { return -1 }
35+
let mut base = 0_usize;
36+
while size > 1 {
37+
let half = size / 2;
38+
let mid = base + half;
39+
if nums[mid] > nums[base] {
40+
base = mid;
41+
}
42+
size -= half;
43+
}
44+
i32::min(nums[base], nums[(base + 1) % nums.len()])
45+
}
46+
}
47+
48+
// submission codes end
49+
50+
#[cfg(test)]
51+
mod tests {
52+
use super::*;
53+
54+
#[test]
55+
fn test_153() {
56+
assert_eq!(Solution::find_min(vec![4,5,6,1,2,3]), 1);
57+
assert_eq!(Solution::find_min(vec![4,5,6,7,0,1,2]), 0);
58+
}
59+
}

0 commit comments

Comments
 (0)