-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1095.cpp
More file actions
108 lines (92 loc) · 2.72 KB
/
1095.cpp
File metadata and controls
108 lines (92 loc) · 2.72 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* // 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 Solution {
public:
unordered_map<int,int> calls;
int peakIndexInMountainArray(MountainArray &ma) {
//divide into three segments, the peak is in whichever 2/3 is
int lo = 0;
int hi = ma.length()-1;
int ans = 0;
while(lo < hi){
int m1 = lo + (hi - lo + 2) / 3;
int m2 = lo + (hi - lo + 1) * 2 / 3;
int a[4] = {lo, m1, m2, hi};
int vals[4] = {};
for(int i = 0; i < 4; i++){
if(calls.count(a[i]) > 0) vals[i] = calls[a[i]];
else{
vals[i] = ma.get(a[i]);
calls[a[i]] = vals[i];
}
}
if(vals[0] > vals[1]){
ans = lo;
hi = m1-1;
} else if(vals[1] >= vals[2]){
ans = m1;
hi = m2-1;
} else if(vals[2] > vals[3]){
ans = m2;
lo = m1+1;
} else {
ans = hi;
lo = m2+1;
}
}
return ans;
}
int findInMountainArray(int target, MountainArray &ma) {
int peak = peakIndexInMountainArray(ma);
calls = unordered_map<int,int>();
//next, binary search in each half of the mountain
int lo = 0;
int hi = peak;
int ans = -1;
while(lo <= hi){
int mid = lo + (hi - lo) / 2;
int val = 0;
if(calls.count(mid) > 0) val = calls[mid];
else{
val = ma.get(mid);
calls[mid] = val;
}
if(val == target){
ans = mid;
hi = mid-1;
} else if(val > target){
hi = mid-1;
} else {
lo = mid+1;
}
}
if(ans != -1) return ans;
lo = peak;
hi = ma.length()-1;
while(lo <= hi){
int mid = lo + (hi - lo) / 2;
int val = 0;
if(calls.count(mid) > 0) val = calls[mid];
else{
val = ma.get(mid);
calls[mid] = val;
}
if(val == target){
ans = mid;
hi = mid-1;
} else if(val < target){
hi = mid-1;
} else{
lo = mid+1;
}
}
return ans;
}
};