162. Find Peak Element
A Peak element is the 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 which case return the "index to" one of the peaks is fine.
May imagine that num[-1] = num[n] =-∞.
For example, in array [1, 2, 3, 1], 3 are a peak element and your function should return the index number 2. iterations
public int findpeakelement (int[] nums) {
int lo = 0, hi = nums.length-1;
Equal while
(lo <= hi) {
//unsigned Right shift ignores sign bit, empty space is 0
int mid = (lo + hi) >>> 1;
If Mid-1 is large, then peak must be between Lo and mid-1 (closed interval)
if (mid-1 >= 0 &&
Nums[mid] < nums[mid-1])
hi = mid-1 ;
If the mid+1 is large, then peak must be between mid+1 and hi (closed interval)
else if (Mid + 1 < nums.length
&& Nums[mid) < Nums[mid + 1]) C13/>lo = mid + 1;
Other cases (peak at the beginning or end, or middle)
else return
mid;
}
return-1;
}
recursion
According to the given condition, Num[i]!= num[i+1], there must, exist a O (LOGN) solution. So we use binary search for this problem. If NUM[I-1] < Num[i] > num[i+1], then Num[i] is peak If num[i-1] < Num[i] < num[i+1], then num[i+1...n-1] must Contains a peak if num[i-1] > Num[i] > num[i+1], then num[0...i-1] must contains a peak If num[i-1] > Num[i] ; Num[i+1], then both sides have peak
(n is num.length)
public int findpeakelement (int[] num) {return
helper (num, 0, num.length-1);
}
public int helper (int[] num, int start, int end) {
//One element
if (start = =) {return
start;
Two elements
} else if (start + 1 = end) {
if (Num[start] > Num[end]) return
start;
return end;
} else {
int m = (start + end)/2;
NUM[I-1] < Num[i] > num[i+1], then Num[i] is peak
if (Num[m] > Num[m-1] && num[m] > num[m + 1]) {return
m;
NUM[I-1] < Num[i] < num[i+1],
//Then num[i+1...n-1] must contains a peak
} else if (num[m-1) > Nu M[M] && Num[m] > num[m + 1] {return
helper (num, start, m-1);
} else {
//other case
//1,num[ I-1] > Num[i] > num[i+1],
//Then Num[0...i-1] must contains a peak
//2,num[i-1] > Num[i] < num[i+1 ],
//Then both sides have peak
//Both sides can, only need to return to the right, the title requires a Return
helper (num, M + 1, end);
}
}
Reference: Https://discuss.leetcode.com/topic/5848/o-logn-solution-javacode