162. Find Peak Element

A peak element is an element that is strictly greater than its neighbors.

Given an integer array nums, find a peak element, and return its index. If the array contains multiple peaks, return the index to any of the peaks.

You may imagine that nums[-1] = nums[n] = -∞.

 

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 5
Explanation: Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.

 

Constraints:

  • 1 <= nums.length <= 1000
  • -231 <= nums[i] <= 231 - 1
  • nums[i] != nums[i + 1] for all valid i.

 

Follow up: Could you implement a solution with logarithmic complexity?

Rust Solution

struct Solution;

impl Solution {
    fn find_peak_element(nums: Vec<i32>) -> i32 {
        let mut l = 0;
        let mut h = nums.len() - 1;
        while l < h {
            let m1 = l + (h - l) / 2;
            let m2 = m1 + 1;
            if nums[m1] < nums[m2] {
                l = m2;
            } else {
                h = m1;
            }
        }
        l as i32
    }
}

#[test]
fn test() {
    let nums = vec![1, 2, 3, 1];
    let res = 2;
    assert_eq!(Solution::find_peak_element(nums), res);
    let nums = vec![1, 2, 1, 3, 5, 6, 4];
    let res = 5;
    assert_eq!(Solution::find_peak_element(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.