当前位置: 代码迷 >> 综合 >> find in mountain array
  详细解决方案

find in mountain array

热度:93   发布时间:2024-01-29 19:52:28.0

 思路:

首先使用二分法找到最高点

然后从最高点左侧进行查找

再从最高点右侧查找

/*** // This is MountainArray's API interface.* // You should not implement it, or speculate about its implementation* interface MountainArray {*     public int get(int index) {}*     public int length() {}* }*/class Solution {public int findInMountainArray(int target, MountainArray mountainArr) {int n = mountainArr.length(),l,r,peek=0;l = 0;r = n-1;while(l<r){int m = (l+r)/2;if(mountainArr.get(m)<mountainArr.get(m+1)){l = peek = m+1;}else{r = m;}}l = 0;r = peek;while(l<=r){int m = (l+r)/2;if(mountainArr.get(m)>target){r = m-1;}else if(mountainArr.get(m)<target){l = m+1;}else{return m;}}l = peek;r = n-1;while(l<=r){int m = (l+r)/2;if(mountainArr.get(m)>target){l = m + 1;}else if(mountainArr.get(m)<target){r = m - 1;}else{return m;}}return -1;}
}

 

  相关解决方案