题目:
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.
Note:
Your solution should be in logarithmic complexity.
思路:
1.查找,时间复杂度O(logn)使用二分法。
2.在如下图所示情况下,有极大值:
3.长度为1时,由于nums[-1]和nums[n]为负无穷,故0即为极大值下标。
4.根据nums[mid]不同情况分析:
(1)nums[mid]比两边数大,mid即为极大值下标。
(2)nums[mid]比左边大,比右边小,极大值可能在mid右侧,故start= mid。
(3)nums[mid]比右边大,比左边小,极大值可能在mid左侧,故end=mid。
(4)nums[mid]比两边都小,根据nums[end]与nums[end-1]判断。
代码:
1 public class Solution { 2 public int findPeakElement(int[] nums) { 3 int start = 0, end = nums.length-1,mid = 0; 4 if(nums.length == 1){ 5 return 0; 6 } 7 while(start + 1 < end){ 8 mid = start + (end - start)/2; 9 if(nums[mid] > nums[mid-1] && nums[mid] > nums[mid+1]){ 10 return mid; 11 }else if(nums[mid] < nums[mid+1] && nums[mid] > nums[mid-1]){ 12 start = mid; 13 }else if(nums[mid] > nums[mid+1] && nums[mid] < nums[mid-1]){ 14 end = mid; 15 }else if(nums[end-1] > nums[end]){ 16 start = mid; 17 }else{ 18 end = mid; 19 } 20 } 21 if(nums[start] > nums[end]){ 22 return start; 23 } 24 return end; 25 } 26 }