- 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
- 60 lines of Java from the credited upstream file 1095.java.
- 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 * interface MountainArray {5 * public int get(int index) {}6 * public int length() {}7 * }8 */9 10class Solution {11 public int findInMountainArray(int target, MountainArray mountainArr) {12 final int n = mountainArr.length();13 final int peakIndex = peakIndexInMountainArray(mountainArr, 0, n - 1);14 15 final int leftIndex = searchLeft(mountainArr, target, 0, peakIndex);16 if (mountainArr.get(leftIndex) == target)17 return leftIndex;18 19 final int rightIndex = searchRight(mountainArr, target, peakIndex + 1, n - 1);20 if (mountainArr.get(rightIndex) == target)21 return rightIndex;22 23 return -1;24 }25 26 27 private int peakIndexInMountainArray(MountainArray A, int l, int r) {28 while (l < r) {29 final int m = (l + r) / 2;30 if (A.get(m) < A.get(m + 1))31 l = m + 1;32 else33 r = m;34 }35 return l;36 }37 38 private int searchLeft(MountainArray A, int target, int l, int r) {39 while (l < r) {40 final int m = (l + r) / 2;41 if (A.get(m) < target)42 l = m + 1;43 else44 r = m;45 }46 return l;47 }48 49 private int searchRight(MountainArray A, int target, int l, int r) {50 while (l < r) {51 final int m = (l + r) / 2;52 if (A.get(m) > target)53 l = m + 1;54 else55 r = m;56 }57 return l;58 }59}60