Let's call an array A
a mountain if the following properties hold:
A.length >= 3
- There exists some
0 < i < A.length - 1
such thatA[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i
such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
.
Input: [0,1,0] Output: 1
Input: [0,2,1,0] Output: 1
3 <= A.length <= 10000
0 <= A[i] <= 106
- A is a mountain, as defined above.
impl Solution {
pub fn peak_index_in_mountain_array(a: Vec<i32>) -> i32 {
let mut i = 1;
while i + 1 < a.len() && a[i] <= a[i + 1] {
i += 1;
}
i as i32
}
}
impl Solution {
pub fn peak_index_in_mountain_array(a: Vec<i32>) -> i32 {
let mut head: usize = 0;
let mut tail = a.len() - 1;
let mut mid: usize;
loop {
mid = (head + tail) / 2;
if a[mid - 1] < a[mid] && a[mid] > a[mid + 1] {
return mid as i32;
} else if a[mid] < a[mid + 1] {
head = mid;
} else if a[mid] > a[mid + 1] {
tail = mid;
}
}
}
}