Skip to content

Commit bf47953

Browse files
committed
🐱(binary-search): 1095. 山脉数组中查找目标值
1 parent ae176cc commit bf47953

File tree

1 file changed

+68
-1
lines changed

1 file changed

+68
-1
lines changed

docs/algorithm/research/binary-search/README.md

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -718,4 +718,71 @@ func getMax(a int, b int) int {
718718
}
719719
```
720720

721-
<!-- tabs:end -->
721+
<!-- tabs:end -->
722+
723+
## 1095. 山脉数组中查找目标值
724+
725+
[原题链接](https://leetcode-cn.com/problems/find-in-mountain-array/)
726+
727+
### 思路
728+
729+
核心思想二分法:
730+
731+
1. 通过二分法寻找峰值
732+
2. 二分法在峰值左侧寻找目标
733+
3. 如果目标不在左侧,使用二分法在峰值右侧寻找目标
734+
735+
```python
736+
# """
737+
# This is MountainArray's API interface.
738+
# You should not implement it, or speculate about its implementation
739+
# """
740+
#class MountainArray:
741+
# def get(self, index: int) -> int:
742+
# def length(self) -> int:
743+
744+
class Solution:
745+
def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
746+
length = mountain_arr.length()
747+
# print(length)
748+
# 找到峰值
749+
left = 0
750+
right = length - 1
751+
while left < right:
752+
mid = (left + right) // 2
753+
if mountain_arr.get(mid + 1) > mountain_arr.get(mid):
754+
# 峰值在右侧
755+
left = mid + 1
756+
else:
757+
right = mid
758+
# 峰值
759+
peak = left
760+
761+
# 左侧二分查找
762+
left = 0
763+
right = peak
764+
while left <= right:
765+
mid = (left + right) // 2
766+
cur = mountain_arr.get(mid)
767+
if cur == target:
768+
return mid
769+
elif cur > target:
770+
right = mid - 1
771+
else:
772+
left = mid + 1
773+
774+
# 右边二分查找:递减数组
775+
left = peak + 1
776+
right = length - 1
777+
while left <= right:
778+
mid = (left + right) // 2
779+
cur = mountain_arr.get(mid)
780+
if cur == target:
781+
return mid
782+
elif cur > target:
783+
left = mid + 1
784+
else:
785+
right = mid - 1
786+
787+
return -1
788+
```

0 commit comments

Comments
 (0)