- 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
- 55 lines of Python from the credited upstream file 1095.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit 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.
12345678 9class Solution:10 def findInMountainArray(11 self,12 target: int,13 mountain_arr: 'MountainArray',14 ) -> int:15 n = mountain_arr.length()16 peakIndex = self.peakIndexInMountainArray(mountain_arr, 0, n - 1)17 18 leftIndex = self.searchLeft(mountain_arr, target, 0, peakIndex)19 if mountain_arr.get(leftIndex) == target:20 return leftIndex21 22 rightIndex = self.searchRight(mountain_arr, target, peakIndex + 1, n - 1)23 if mountain_arr.get(rightIndex) == target:24 return rightIndex25 26 return -127 28 29 def peakIndexInMountainArray(self, A: 'MountainArray', l: int, r: int) -> int:30 while l < r:31 m = (l + r) 232 if A.get(m) < A.get(m + 1):33 l = m + 134 else:35 r = m36 return l37 38 def searchLeft(self, A: 'MountainArray', target: int, l: int, r: int) -> int:39 while l < r:40 m = (l + r) 241 if A.get(m) < target:42 l = m + 143 else:44 r = m45 return l46 47 def searchRight(self, A: 'MountainArray', target: int, l: int, r: int) -> int:48 while l < r:49 m = (l + r) 250 if A.get(m) > target:51 l = m + 152 else:53 r = m54 return l55