描述
给 n 个整数的山脉数组,即先增后减的序列,找到山顶(最大值)
您在真实的面试中是否遇到过这个题?
样例
例1:
输入: nums = [1, 2, 4, 8, 6, 3]
输出: 8
例2:
输入: nums = [10, 9, 8, 7],
输出: 10
实现:
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
if (nums == null || nums.length == 0) {
return -1;
}
int start = 0;
int end = nums.length - 1;
while (start + 1 < end) {
int mid = start + (end - start) / 2;
if (nums[mid] > nums[mid - 1]) {
start = mid;
}
if (nums[mid] > nums[mid + 1]) {
end = mid;
}
}
return Math.max(nums[start], nums[end]);
}
}
网友评论