題目:
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.
Your solution should be in logarithmic complexity.
思路:要求時間複雜度O(logN),立刻就想到了Binary Search
取mid,然後判斷nums[mid-1] nums[mid] nums[mid+1]之間的大小,判斷mid位於巔峯的左側還是右側。
要注意的細節,因爲mid可能會是0,導致nums[mid-1]越界,所以要處理
代碼:
public int findPeakElement(int[] nums) {
int left=0;
int right=nums.length-1;
while(left<right){
//亦可以提前結束循環,這樣不會出現mid=0的情況
// if(left+1==right)
// return (nums[left]>nums[right])?left:right;
int mid = left+((right-left)>>1);
if(mid==0){//當出現mid=0要特殊處理,不然mid-1會越界
return (nums[0]>nums[1])?0:1;
}
if(nums[mid]>nums[mid-1]&&nums[mid]>nums[mid+1])
return mid;
if(nums[mid-1]<nums[mid+1]){//上升階段
left=mid+1;
}else{//下降階段
right=mid-1;
}
}
return left;
}