/** * // 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(); * }; */
classSolution { public: intfindInMountainArray(int target, MountainArray &mountainArr){ int n = mountainArr.length(); int left = 0, right = n - 1; int ans = -1; int topIndex = -1, topValue = 0;
while (left <= right) { int mid = (left + right) / 2; int midv = mountainArr.get(mid); int midrv = mountainArr.get(mid + 1); if (midv < midrv) { left = mid + 1; topIndex = mid + 1; topValue = midrv; } else { int midlv = mountainArr.get(mid - 1); if (midv < midlv) { right = mid - 1; topIndex = mid - 1; topValue = midlv; } else { topIndex = mid; topValue = midv; break; } } }