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.
算法複雜度應在Logn內。所以猜想應該是用遞歸或者分治。注意題目有一個條件是很特殊的。就是Num[n]!=Num[n+1]
也就是說。要麼大於 要麼小於。第二個就是
You may imagine that num[-1] = num[n] = -∞
.
先把能寫的寫了。
第一個就是判定規則,很簡單
if(num[i]>num[i-1]&&num[i]>num[i+1]){
return num[i];
}
那麼其實問題的關鍵在於查找方式。
我仍然想試一下遍歷。但是因爲有某種情況是可以做到skip的遍歷。所以我認爲這種情況是小於n的。但是能不能達到logn就不知道了。想試一下。
然後。就過了!!!你敢信!!就過了。。==。而且。。
public static int findPeakElement(int[] num) {
for (int j = 0; j < num.length; j++) {
if (num.length == 1) {
return 0;
} else if (j == 0) {
if (num[0] > num[1]) {
return 0;
}
} else if (j == num.length - 1) {
if (num[num.length - 1] > num[num.length - 2]) {
return num.length - 1;
}
} else if (num[j] > num[j - 1] && num[j] > num[j + 1]) {
return j;
}
}
return num.length - 1;
}
這題到底難在哪啊。。。=0=