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. 迭代
public int findPeakElement(int[] nums) {int lo = 0, hi = nums.length - 1;// 等號while (lo <= hi) {// 無符號右移,忽略符號位,空位都以0補齊int mid = (lo + hi) >>> 1;// 如果mid-1大,那麼peak肯定在lo和mid-1之間(閉區間)if (mid - 1 >= 0 &&nums[mid] < nums[mid - 1])hi = mid - 1;// 如果mid+1大,那麼peak肯定在mid+1和hi之間(閉區間)else if (mid + 1 < nums.length&& nums[mid] < nums[mid + 1])lo = mid + 1;// 其他情況(peak在開頭或者結尾,或者中間)elsereturn mid;}return -1;}
遞迴
according to the given condition, num[i] != num[i+1], there must exist a O(logN) solution. So we use binary search for this problem. If num[i-1] < num[i] > num[i+1], then num[i] is peak If num[i-1] < num[i] < num[i+1], then num[i+1...n-1] must contains a peak If num[i-1] > num[i] > num[i+1], then num[0...i-1] must contains a peak If num[i-1] > num[i] < num[i+1], then both sides have peak
(n is num.length)
public int findPeakElement(int[] num) {return helper(num, 0, num.length - 1);}public int helper(int[] num, int start, int end) {// 一個元素if (start == end) {return start;// 兩個元素} else if (start + 1 == end) {if (num[start] > num[end])return start;return end;} else {int m = (start + end) / 2;// num[i-1] < num[i] > num[i+1], then num[i] is peakif (num[m] > num[m - 1] && num[m] > num[m + 1]) {return m;// num[i-1] < num[i] < num[i+1],// then num[i+1...n-1] must contains a peak} else if (num[m - 1] > num[m] && num[m] > num[m + 1]) {return helper(num, start, m - 1);} else {// 其他情況// 1,num[i-1] > num[i] > num[i+1],// then num[0...i-1] must contains a peak// 2,num[i-1] > num[i] < num[i+1],// then both sides have peak// 兩邊都可以,只需要返回右邊即可,題目要求返回一個,return helper(num, m + 1, end);}}}
參考:https://discuss.leetcode.com/topic/5848/o-logn-solution-javacode