-
Notifications
You must be signed in to change notification settings - Fork 0
/
852. Peak Index in a Mountain Array
55 lines (40 loc) · 1.1 KB
/
852. Peak Index in a Mountain Array
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
48
49
50
51
52
53
54
55
/***************************************************
An array arr a mountain if the following properties hold:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given a mountain array arr, return the index i such that arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1].
You must solve it in O(log(arr.length)) time complexity.
Example 1:
Input: arr = [0,1,0]
Output: 1
Example 2:
Input: arr = [0,2,1,0]
Output: 1
Example 3:
Input: arr = [0,10,5,2]
Output: 1
Constraints:
3 <= arr.length <= 105
0 <= arr[i] <= 106
arr is guaranteed to be a mountain array.
************************************************
class Solution {
public:
int peakIndexInMountainArray(vector<int>& arr) {
int s=0;
int e=arr.size()-1;
int mid=s+(e-s)/2;
while(s<e){
if(arr[mid]<arr[mid+1]){
s=mid+1;
}
else{
e=mid;
}
mid=s+(e-s)/2;
}
return s;
}
};