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 public class Solution { 2 public int findPeakElement(int[] nums) { 3 return helper(nums,0,nums.length-1); 4 } 5 public int helper(int[] nums,int left,int right){ 6 if(left==right) return left;// 7 int mid1 = left+(right-left)/2;// 8 int mid2 = mid1+1; 9 if(nums[mid1]<nums[mid2]){ 10 return helper(nums,mid2,right); 11 }else{ 12 return helper(nums,left,mid1); 13 } 14 } 15 }
第六行需要注意的是,如果数组里面只有一个元素,就直接返回。
第七行需要注意的是,mid1指向的如果是奇数总数的中位数,那么就是中间的,如果是偶数个总数的中位数,那么指向的中位数是偏左那个。
迭代做法如下:
1 public class Solution { 2 public int findPeakElement(int[] nums) { 3 int left = 0; 4 int right = nums.length-1; 5 while(left < right) { 6 int mid = left + ( right - left ) / 2; 7 if( nums[mid] < nums[mid+1] ){ 8 left = mid + 1; 9 }else{ 10 right = mid; 11 } 12 } 13 return left; 14 } 15 } 16 // run time complexity could be O(logn), space complexity could be O(1);