Skip to content

Latest commit

 

History

History
59 lines (52 loc) · 1.52 KB

File metadata and controls

59 lines (52 loc) · 1.52 KB

852. Peak Index in a Mountain Array

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 that A[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].

Example 1:

Input: [0,1,0]
Output: 1

Example 2:

Input: [0,2,1,0]
Output: 1

Note:

  1. 3 <= A.length <= 10000
  2. 0 <= A[i] <= 106
  3. A is a mountain, as defined above.

Solutions (Rust)

1. Linear Scan

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
    }
}

2. Binary Search

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;
            }
        }
    }
}