fn find_peak_element(nums: &[i32]) -> usize {
let mut left = 0;
let mut right = nums.len() - 1;
while left < right {
let mid = (left + right) / 2;
if nums[mid] > nums[mid + 1] {
right = mid;
} else {
left = mid + 1;
}
}
left
}
fn main() {
let nums = [1, 3, 20, 4, 1, 0];
let peak_index = find_peak_element(&nums);
println!("{}", peak_index);
}The function uses binary search to find a peak element index. It compares the middle element with the next one. If the middle is greater, the peak is on the left side including mid; otherwise, it's on the right side. For the array [1, 3, 20, 4, 1, 0], the peak is at index 2 (value 20).
A peak element is strictly greater than its neighbors. Option C correctly states this condition. Other options either use or conditions or check for equality or smaller values, which do not define a peak.
fn find_peak_element(nums: &[i32]) -> usize {
let mut left = 0;
let mut right = nums.len();
while left < right {
let mid = (left + right) / 2;
if nums[mid] > nums[mid + 1] {
right = mid;
} else {
left = mid + 1;
}
}
left
}
fn main() {
let nums = [1, 2, 3, 1];
let peak_index = find_peak_element(&nums);
println!("{}", peak_index);
}The code sets right to nums.len(), which is out of bounds for indexing. When mid equals nums.len() - 1, mid + 1 equals nums.len(), causing an index out of bounds panic.
Option A correctly uses while left < right and updates left and right pointers safely. It avoids index out of bounds and infinite loops. Other options either use wrong loop conditions or unsafe indexing.
Binary search compares the middle element with its neighbor to decide which half contains a peak, reducing the search space logarithmically. Linear scan is O(n), sorting is O(n log n) and does not guarantee peak, recursion checking all elements is inefficient.
