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
|
class Solution { public: template<typename Func> int binary_search(MountainArray& mountainArr, int target, int l, int r, Func func) { target = func(target); while (l <= r) { int mid = (l + r) / 2; int cur = func(mountainArr.get(mid)); if (cur == target) return mid; if (cur < target) l = mid + 1; else r = mid - 1; } return -1; }
int findInMountainArray(int target, MountainArray &mountainArr) { int l = 0, r = mountainArr.length() - 1; while (l < r) { int mid = (l + r) / 2; if (mountainArr.get(mid) < mountainArr.get(mid + 1)) { l = mid + 1; } else { r = mid; } } int peak = l; int index = binary_search(mountainArr, target, 0, peak, [](int x) { return x; }); if (index != -1) return index; index = binary_search(mountainArr, target, peak + 1, mountainArr.length() - 1, [](int x) { return -x; }); return index; } };
|