@@ -4,29 +4,31 @@ public class _162 {
4
4
5
5
public static class Solution1 {
6
6
/**
7
- * credit: https://discuss.leetcode.com/topic/29329/java-solution-and-explanation-using-invariants
8
- * <p>
9
- * Basically, we need to keep this invariant:
10
- * nums[left] > nums[left-1], then we could return left as the result
11
- * or nums[right] > nums[right+1], then we could return right as the result
12
- * <p>
7
+ * credit: https://leetcode.com/problems/find-peak-element/solutions/1290642/intuition-behind-conditions-complete-explanation-diagram-binary-search/
13
8
* Time: O(logn)
9
+ * <p>
10
+ * draw three cases with three examples, it's pretty self-explanatory
14
11
*/
15
12
public int findPeakElement (int [] nums ) {
16
- if (nums == null || nums .length == 0 ) {
13
+ if (nums == null || nums .length <= 1 || nums [ 0 ] > nums [ 1 ] ) {
17
14
return 0 ;
18
15
}
19
- int left = 0 ;
20
- int right = nums .length - 1 ;
21
- while (left + 1 < right ) {
16
+ if (nums [nums .length - 1 ] > nums [nums .length - 2 ]) {
17
+ return nums .length - 1 ;
18
+ }
19
+ int left = 1 ;
20
+ int right = nums .length - 2 ;
21
+ while (left <= right ) {
22
22
int mid = left + (right - left ) / 2 ;
23
- if (nums [mid ] < nums [mid + 1 ]) {
24
- left = mid ;
25
- } else {
26
- right = mid ;
23
+ if (nums [mid ] > nums [mid - 1 ] && nums [mid ] > nums [mid + 1 ]) {
24
+ return mid ;
25
+ } else if (nums [mid ] < nums [mid - 1 ]) {
26
+ right = mid - 1 ;
27
+ } else if (nums [mid ] < nums [mid + 1 ]) {
28
+ left = mid + 1 ;
27
29
}
28
30
}
29
- return ( left == nums . length - 1 || nums [ left ] > nums [ left + 1 ]) ? left : right ;
31
+ return - 1 ;
30
32
}
31
33
}
32
34
0 commit comments