標籤:style blog ar io color sp for on div
Find Peak Element
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.
我自己寫的就比較挫一點了,這道題要用二分尋找來實現。但我一直沒有明白為什麼可以用二分尋找實現
1 public class Solution { 2 public int findPeakElement(int[] num) { 3 if(num.length == 0 || num.length == 1) 4 return 0; 5 boolean isIncr = false; //是否為升序 6 int index = -1; //peak索引值 7 int numArray[] = new int[num.length + 2]; 8 for(int i = 0; i < num.length;i++){ 9 numArray[i + 1] = num[i];10 }11 numArray[0] = Integer.MIN_VALUE;12 numArray[numArray.length - 1] = Integer.MIN_VALUE;13 14 for(int i = 1; i < numArray.length;i++){15 if(numArray[i] > numArray[i - 1])16 isIncr = true;17 if(isIncr && numArray[i] < numArray[i - 1]){18 index = i - 2;19 break;20 }21 }22 23 return index;24 }25 }
下面這個是百度到的,好像是CSDN還是哪兒的,我就懶得去找源出處了。這個時間複雜度是O(N)
1 public class Solution {2 public int findPeakElement(int[] num) {3 for(int i = 1; i < num.length; i++){4 if(num[i] < num[i - 1])5 return i - 1;6 }7 return num.length - 1;8 }9 }
下面這個是討論區用二分尋找實現的
1 public class Solution { 2 public int findPeakElement(int[] num) { 3 int low = 0; 4 int high = num.length - 1; 5 while (low < high) { 6 int mid = (low + high + 1)/2; 7 if (mid == 0 || num[mid] > num[mid-1]) { 8 low = mid; 9 } else {10 high = mid-1;11 }12 }13 return low;14 }15 }
Find Peak Element