leetcode [162]Find Peak Element
A peak element is an element that is greater than its neighbors.
Given an input array nums
, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞
.
Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:
Input: nums = [
1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.
Note:
Your solution should be in logarithmic complexity.
题目大意:
找到数组中的峰值,一个数组中可能会有多个峰值,返回一个就可以了。
解法:
按顺序找到数组中比左右两边的数大的数字,返回该数字的下标就行了。
java:
class Solution { public int findPeakElement(int[] nums) { if(nums.length==1) return 0; if(nums[0]>nums[1]) return 0; if(nums[nums.length-1]>nums[nums.length-2]) return nums.length-1; for(int i=1;i<nums.length-1;i++){ if(nums[i]>nums[i+1]&&nums[i]>nums[i-1]) return i; } return 0; } }
顺序查找的代码可简化为:
class Solution { public int findPeakElement(int[] nums) { int i=1; for(;i<nums.length;i++){ if(nums[i]<nums[i-1]) break; } return i-1; } }
但是题目的附加要求是解法的复杂度应该是对数级别的,应该使用二分查找。
java:
递归的二分查找:
class Solution { int helper(int[]nums,int start,int end){ if(start==end) return start; int mid1=(start+end)/2; int mid2=mid1+1; if(nums[mid1]>nums[mid2]) return helper(nums,start,mid1); else return helper(nums,mid2,end); } public int findPeakElement(int[] nums) { return helper(nums,0,nums.length-1); } }
非递归的二分查找:
class Solution { public int findPeakElement(int[] nums) { int start=0,end=nums.length-1; while(start<end){ int mid=(start+end)/2; if(nums[mid]>nums[mid+1]) end=mid; else start=mid+1; } return start; } }