A peak element is an element that is greater than its neighbors.
Given an input array nums
, where nums[i] ≠ nums[i+1]
, find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
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: 1 or 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.
//Time: O(logn), Space: O(1)
1 public int findPeakElement(int[] nums) { 2 if (nums == null || nums.length == 0) { 3 return -1; 4 } 5 6 int start = 0; 7 int end = nums.length - 1; 8 9 while (start < end) {//因为有[1]这种特殊情况,所以要start<end, 直接跳出循环 10 int mid = start + (end - start) / 2; 11 if (nums[mid] < nums[mid + 1]) { 12 start = mid + 1; 13 } else { 14 end = mid; 15 } 16 } 17 18 return start; 19 } 20 //注意:test cases 21 // 1. [] -- -1 22 // 2. [1] -- 0 23 // 3. [1,2] -- 1 24 // 4. [2, 1] -- 0 25 // 5. [1,2,1] -- 1 26 // 6. [1,2,3,1] -- 2
similar: 852. Peak Index in a Mountain Array