-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1095.find-in-mountain-array.cpp
More file actions
82 lines (76 loc) · 1.7 KB
/
1095.find-in-mountain-array.cpp
File metadata and controls
82 lines (76 loc) · 1.7 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* @lc app=leetcode id=1095 lang=cpp
*
* [1095] Find in Mountain Array
*/
// @lc code=start
/**
* // This is the MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* class MountainArray {
* public:
* int get(int index);
* int length();
* };
*/
class Arr {
MountainArray &mountainArr;
map<int, int> arr;
public:
Arr(MountainArray &m): mountainArr(m) {}
int &operator[](int index) {
if(arr.count(index)) return arr[index];
arr[index] = mountainArr.get(index);
return arr[index];
}
};
class Solution {
public:
int findInMountainArray(int target, MountainArray &mountainArr) {
Arr a(mountainArr);
int len = mountainArr.length();
int low = 1;
int high = len - 2;
int peak;
while(low <= high) {
int mid = (low + high) / 2;
if(a[mid] > a[mid - 1] && a[mid] > a[mid + 1]) {
peak = mid;
break;
} else if(a[mid] > a[mid - 1]) {
low = mid + 1;
} else {
high = mid - 1;
}
}
low = 0;
high = peak;
while(low < high) {
int mid = (low + high) / 2;
if(a[mid] < target) {
low = mid + 1;
} else {
high = mid;
}
}
cout << low << ' ' << high << endl;
if(a[low] == target) return low;
low = peak;
high = len - 1;
while(low < high) {
int mid = (low + high) / 2;
if(a[mid] > target) {
low = mid + 1;
} else {
high = mid;
}
}
if(a[low] == target) return low;
return -1;
}
};
// Accepted
// 79/79 cases passed (0 ms)
// Your runtime beats 100 % of cpp submissions
// Your memory usage beats 14.97 % of cpp submissions (7.5 MB)
// @lc code=end