A peak element is an element, which 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 be contain multiple peaks, in this case return the index to any one of the peaks is fine.
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.
Idea 1: Traversal, O (N)
Code Listing 1:
public int findPeakElement1 (int[] num) {//Violence for (int i = 0; i < num.length; ++i) { if (I+1 < num.length) { if (Num[i] > Num[i+1] && ((i-1 >= 0 && num[i] > num[i-1]) | | (I-1 < 0))) { return i; } } else { if (i-1 < 0 | | i-1 >=0 && num[i] > Num[i-1]) { return i;}} } return 0; }
Idea 2: two points,
Code:
public int findpeakelement (int[] num) {// int l = 0, R = num.length-1, mid; while (L < R) { mid = L + (r-l)/2; if (Num[mid] < Num[mid + 1]) L = mid + 1; else R = Mid; } return num[l]; }
[Leetcode] Find Peak Element