162. Find Peak Element
A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[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 num[-1] = num[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
分析:一般解法:
由于最左边最小值是-∞,所以最先的时候,array是单调递增的。只要我们找到第一个 nums[i] > nums[i + 1] ,那么就把答案找到了。
public class Solution { public int findPeakElement(int[] nums) { for (int i = 0; i < nums.length - 1; i++) { if (nums[i] > nums[i + 1]) return i; } return nums.length - 1; } }
O(lgN)解法
1 public class Solution { 2 public int findPeakElement(int[] nums) { 3 int l = 0, r = nums.length - 1; 4 while (l < r) { 5 int mid = (l + r) / 2; 6 //as nums[-1] and nums[length] is negative infinity, if nums[mid] > nums[mid + 1], then there is a peak 7 if (nums[mid] > nums[mid + 1]) 8 r = mid; 9 else 10 l = mid + 1; 11 } 12 return l; 13 } 14 }