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
| class Solution { public: int findInMountainArray(int target, MountainArray &mountainArr) { const int n = mountainArr.length(); int topIndex = findTopIndex(mountainArr, 0, n - 1); if (mountainArr.get(topIndex) == target) return topIndex; int idx = findFromSortedArr(mountainArr, 0, topIndex - 1, target); if (idx >= 0) return idx; return findFromReversedArr(mountainArr, topIndex + 1, n - 1, target); } private: int findTopIndex(MountainArray& mountainArr, int left, int right) { while (left < right) { int mid = (right - left) / 2 + left; if (mountainArr.get(mid) < mountainArr.get(mid + 1)) left = mid + 1; else right = mid; } return left; }
int findFromSortedArr(MountainArray& mountainArr, int left, int right, int target) { while (left < right) { int mid = (right - left) / 2 + left; if (mountainArr.get(mid) < target) left = mid + 1; else right = mid; } return mountainArr.get(left) == target ? left : -1; }
int findFromReversedArr(MountainArray& mountainArr, int left, int right, int target) { while (left < right) { int mid = (right - left + 1) / 2 + left; if (mountainArr.get(mid) < target) right = mid - 1; else left = mid; } return mountainArr.get(left) == target ? left : -1; } };
|