返回旋转数组的最小元素
示例 1:
输入:numbers = [3,4,5,1,2]
输出:1
示例 2:
输入:numbers = [2,2,2,0,1]
输出:0
题目
[https://leetcode.cn/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/]
//两个思路,一个是二分查找,另一个是普通线性查找
impl Solution {
pub fn min_array(numbers: Vec<i32>) -> i32 {
// 二分查找
let mut left:usize = 0;
let mut right = numbers.len() - 1;
while left < right{
let mut middle = (left + right) / 2;
if numbers[right] > numbers[middle]{
right = middle;
}else if numbers[right] < numbers[middle]{
left = middle + 1;
}else{
right -= 1;
}
}
return numbers[right];
}
}
// 其他线性查找的方法 [https://leetcode.cn/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/solution/rust-by-ruislan-67/](https://leetcode.cn/problems/xuan-zhuan-shu-zu-de-zui-xiao-shu-zi-lcof/solution/rust-by-ruislan-67/)
impl Solution {
pub fn min_array(numbers: Vec<i32>) -> i32 {
// 1
let mut numbers = numbers;
let result = numbers.iter().min().unwrap();
*result
// 2
let mut numbers = numbers;
let result = numbers.into_iter().min().unwrap();
result
// 3
let mut numbers = numbers;
numbers.sort();
if numbers.is_empty(){
0
}else{
numbers[0]
}
// 4
let mut min = if numbers.is_empty() { 0 } else {numbers[0]};
numbers.into_iter().for_each(|x | if x < min {min = x });
min
}
}
网友评论