classSolution {
publicintfindMinInValleyArray(int[] arr) {
int left = 0;
int right = arr.length- 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid]< arr[mid + 1]) {
// Trough must be in the left half, including mid right = mid;
} else {
// Trough must be in the right half, excluding mid left = mid + 1;
}
}
// Left (or right) will be the index of the trough elementreturn left;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
deffindMaxInBitonicArray(self, arr: List[int]) -> int:
left, right =0, len(arr) -1while left < right:
mid = (left + right) //2if arr[mid] > arr[mid +1]:
# Peak must be in the left half, including mid right = mid
else:
# Peak must be in the right half, excluding mid left = mid +1# Left (or right) will be the index of the peak elementreturn left