題目:
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] = -∞.
Example1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example2:
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.
思路:
本題有兩種解法敞贡。首先自然是非常簡單粗暴的一個一個找甸鸟,并且比較兩邊的元素照弥。找到一個符合條件的就break出循環(huán)粱栖。但是注意最后需要控制好邊界绘沉。結(jié)果雖然過了但是整個算法跑的非常慢贴浙。
本題推薦使用第二種解法译红,也就是二分法來解決。首先找到中間元素設(shè)為mid铃将,如果mid位置上的元素大于mid+1上的元素徽曲,則說明咱們要找的目標(biāo)元素可能在左邊,此時將right設(shè)為mid麸塞。反之,如果mid+1上的元素大于mid上的元素涧衙,則目標(biāo)元素可能在右邊哪工,此時將left設(shè)為mid+1。最后返回位置left弧哎。
代碼:
/**
* Find peak element
* @param nums
* @return
*/
public int findPeakElement(int[] nums) {
if(nums == null || nums.length == 0)
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;
}