给 n
个整数的山脉数组,即先增后减的序列,找到山顶(最大值)
样例
给出数组为 [1, 2, 4, 8, 6, 3]
,返回 8
给出数组为 [10, 9, 8, 7]
,返回 10
解题思路:
与Lintcode 75. 寻找峰值类似,典型的二分搜索,因为mid的值总会偏向左方,所以大胆l = mid + 1;总会遍历到这个值的。
public class Solution {
/**
* @param nums: a mountain sequence which increase firstly and then decrease
* @return: then mountain top
*/
public int mountainSequence(int[] nums) {
// write your code here
int l = 0, r = nums.length-1;
while(l < r){
int mid = l + ((r-l)>>>1);
if(mid-1 >= 0 && nums[mid] > nums[mid-1] && nums[mid] > nums[mid+1])
return nums[mid];
if(nums[mid] > nums[mid+1])
r = mid - 1;
else
l = mid + 1;
}
return nums[l];
}
}