|
| 1 | +/** |
| 2 | + * [162] Find Peak Element |
| 3 | + * |
| 4 | + * A peak element is an element that is greater than its neighbors. |
| 5 | + * |
| 6 | + * Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index. |
| 7 | + * |
| 8 | + * The array may contain multiple peaks, in that case return the index to any one of the peaks is fine. |
| 9 | + * |
| 10 | + * You may imagine that nums[-1] = nums[n] = -∞. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * |
| 14 | + * |
| 15 | + * Input: nums = [1,2,3,1] |
| 16 | + * Output: 2 |
| 17 | + * Explanation: 3 is a peak element and your function should return the index number 2. |
| 18 | + * |
| 19 | + * Example 2: |
| 20 | + * |
| 21 | + * |
| 22 | + * Input: nums = [1,2,1,3,5,6,4] |
| 23 | + * Output: 1 or 5 |
| 24 | + * Explanation: Your function can return either index number 1 where the peak element is 2, |
| 25 | + * or index number 5 where the peak element is 6. |
| 26 | + * |
| 27 | + * |
| 28 | + * Note: |
| 29 | + * |
| 30 | + * Your solution should be in logarithmic complexity. |
| 31 | + * |
| 32 | + */ |
| 33 | +pub struct Solution {} |
| 34 | + |
| 35 | +// submission codes start here |
| 36 | + |
| 37 | +impl Solution { |
| 38 | + pub fn find_peak_element(nums: Vec<i32>) -> i32 { |
| 39 | + let (mut lo, mut hi) = (0_usize, nums.len() - 1); |
| 40 | + let mut mid = 0; |
| 41 | + while lo < hi { |
| 42 | + mid = (hi - lo) / 2 + lo; |
| 43 | + if mid + 1 < nums.len() && nums[mid] < nums[mid+1]{ |
| 44 | + lo = mid + 1; |
| 45 | + } else { |
| 46 | + hi = mid; |
| 47 | + } |
| 48 | + } |
| 49 | + lo as i32 |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// submission codes end |
| 54 | + |
| 55 | +#[cfg(test)] |
| 56 | +mod tests { |
| 57 | + use super::*; |
| 58 | + |
| 59 | + #[test] |
| 60 | + fn test_162() { |
| 61 | + assert_eq!(Solution::find_peak_element(vec![1,2,3,1]), 2); |
| 62 | + assert_eq!(Solution::find_peak_element(vec![1,2,1,3,5,6,4]), 5); |
| 63 | + } |
| 64 | +} |
0 commit comments