- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 64 lines of C++ from the credited upstream file 1095.cpp.
- The implementation keeps its working state in language-native values and containers.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1/**2 * 3 * 4 * class MountainArray {5 * public:6 * int get(int index);7 * int length();8 * };9 */10 11class Solution {12 public:13 int findInMountainArray(int target, MountainArray& mountainArr) {14 const int n = mountainArr.length();15 const int peakIndex = peakIndexInMountainArray(mountainArr, 0, n - 1);16 17 const int leftIndex = searchLeft(mountainArr, target, 0, peakIndex);18 if (mountainArr.get(leftIndex) == target)19 return leftIndex;20 21 const int rightIndex =22 searchRight(mountainArr, target, peakIndex + 1, n - 1);23 if (mountainArr.get(rightIndex) == target)24 return rightIndex;25 26 return -1;27 }28 29 private:30 31 int peakIndexInMountainArray(MountainArray& A, int l, int r) {32 while (l < r) {33 const int m = (l + r) / 2;34 if (A.get(m) < A.get(m + 1))35 l = m + 1;36 else37 r = m;38 }39 return l;40 }41 42 int searchLeft(MountainArray& A, int target, int l, int r) {43 while (l < r) {44 const int m = (l + r) / 2;45 if (A.get(m) < target)46 l = m + 1;47 else48 r = m;49 }50 return l;51 }52 53 int searchRight(MountainArray& A, int target, int l, int r) {54 while (l < r) {55 const int m = (l + r) / 2;56 if (A.get(m) > target)57 l = m + 1;58 else59 r = m;60 }61 return l;62 }63};64