You may recall that an array arr is a mountain array if and only if:
arr.length >= 3
There exists some i with 0 < i < arr.length - 1 such that:
arr[0] < arr[1] < … < arr[i - 1] < arr[i]
arr[i] > arr[i + 1] > … > arr[arr.length - 1]
Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) == target. If such an index does not exist, return -1.
You cannot access the mountain array directly. You may only access the array using a MountainArray interface:
MountainArray.get(k) returns the element of the array at index k (0-indexed).
MountainArray.length() returns the length of the array.
Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification.
/** * // 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 { inttop(MountainArray &A, int l, int r){ while(l < r) { int m = (l + r) / 2; if(A.get(m) > A.get(m + 1)) { r = m; } else { l = m + 1; } } return l; } intbinarySearch(MountainArray &A, int l, int r, int t){ while(l <= r) { int m = (l + r) / 2, mv = A.get(m); if(mv == t) return m; elseif(mv < t) l = m + 1; else r = m - 1; } return - 1; } intreverseBinarySearch(MountainArray &A, int l, int r, int t){ while(l <= r) { int m = (l + r) / 2, mv = A.get(m); if(mv == t) return m; elseif(mv < t) r = m - 1; else l = m + 1; } return-1; } public: intfindInMountainArray(int t, MountainArray &A){ int n = A.length(); int l = 0, r = n-1, m = top(A,l,r); int bS = binarySearch(A,l,m,t); if(bS == -1) returnreverseBinarySearch(A,m+1,r,t); return bS; } };