File tree Expand file tree Collapse file tree 1 file changed +68
-1
lines changed
docs/algorithm/research/binary-search Expand file tree Collapse file tree 1 file changed +68
-1
lines changed Original file line number Diff line number Diff line change @@ -718,4 +718,71 @@ func getMax(a int, b int) int {
718
718
}
719
719
```
720
720
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
+ ```
You can’t perform that action at this time.
0 commit comments