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,2,3,1],山頂元素為3
題解:
會有三種情況:
- 有山頂:[1,5,2,3,1]=>5
- 右偏斜:[4,2,3,1]=>4
- 左偏斜:[1,3,2,5,7]=>7
依照以上三種情況來編寫代碼
package LeetCode.Medium;
/*
* 山峰型,返回山頂數字的index
* ex:12321
* return 2
* ex:12323421
* return 5
*
* 右偏斜型,返回第0個
* ex:321
* return 0
* 左偏斜型,返回最後一個
* ex:123
* return 2
*/
public class FindPeakElement {
public int findPeakElement(int[] nums) {
boolean isSkew = true;
int peak_index = 0;
//開始尋找山頂
for(int i = 1; i < nums.length; i ++) {
if(i + 1 >= nums.length) {
break;
}
//若找到山頂則不是偏斜
if(nums[i - 1] < nums[i] && nums[i] > nums[i + 1]) {
peak_index = i;
isSkew = false;
break;
}
}
//̎處理偏斜的部分
if(isSkew == true && nums.length > 1) {
if(nums[0] > nums[1]) {
peak_index = 0;
} else if(nums[1] > nums[0]){
peak_index = nums.length - 1;
}
}
return peak_index;
}
}