-
Notifications
You must be signed in to change notification settings - Fork 1
/
PeakIndexMountainArray.java
47 lines (40 loc) · 1.31 KB
/
PeakIndexMountainArray.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package interview;
public class PeakIndexMountainArray {
//https://leetcode.com/problems/peak-index-in-a-mountain-array/
//Also refer https://leetcode.com/problems/find-peak-element/
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int n = arr.length;
int l = 0;
int r = n-1;
while(l<r){
int mid = l + (r-l)/2;
if(arr[mid] < arr[mid+1]){
//number are increasin so peak is on right
l = mid +1;
}else{
//mid or number before it is peak
r = mid;
}
}
return r; // or return l;
}
}
//when length >=3
class Solution2 {
public int peakIndexInMountainArray(int[] arr) {
int n = arr.length;
int l = 0;
int r = n -1;
while(l<=r){
int mid = l + (r-l)/2;
if(arr[mid] < arr[mid+1]){
l = mid + 1; //we are going -ve slope so peak on left
}else{
r = mid -1; // we are on +ve slope so peak on right
}
}
return r < n-1 ? r+1 : n-1; //end of loop we cross over the peak so r+1 .
}
}
}