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.
Note:
Your solution should be in logarithmic complexity.
Solution: Binary search
如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧必包含一个局部最大值。
时间复杂度O(logN), constant space.
如果中间元素大于其相邻后续元素,则中间元素左侧(包含该中间元素)必包含一个局部最大值。如果中间元素小于其相邻后续元素,则中间元素右侧必包含一个局部最大值。
时间复杂度O(logN), constant space.
public class Solution { public int findPeakElement(int[] num) { if(num == null) return 0; int L = 0, R = num.length - 1; while(L <= R) { if(L == R) return L; int mid = (L + R) / 2; if(num[mid] <= num[mid + 1]) { L = mid + 1; //if num[mid]<=num[mid + 1], peak element must on the right side }else { R = mid; //otherwise, peak element must on the left side } } return 0; } }Or:
public class Solution { public int findPeakElement(int[] nums) { if (nums == null || nums.length <= 1) { return 0; } int left = 0; int right = nums.length - 1; while(left < right) { int mid = (left + right) / 2; if (nums[mid] < nums[mid + 1]) { left = mid + 1; } else { right = mid; } } return left; } }
No comments:
Post a Comment