描述
给 n 个整数的山脉数组,即先增后减的序列,找到山顶(最大值)
样例
给出数组为 [1, 2, 4, 8, 6, 3],返回 8
给出数组为 [10, 9, 8, 7],返回 10
代码
方法1
public class Solution {
/**
* @param nums a mountain sequence which increase firstly and then decrease
* @return then mountain top
*/
public int mountainSequence(int[] nums) {
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;
/* 应注意条件语句写法
* 若写成nums[mid] < nums[mid - 1] 和nums[mid] < nums[mid + 1];
* 在mid是最大值时,start和end都不更新,死循环
* 写下面if条件时要保证同时只满足一个条件
* 不会出现同时满足两个和不满足两个的情形
*/
// 保证mid取顶点时 ,不会出现死循环
if (nums[mid] > nums[mid - 1]) {
start = mid;
}
if (nums[mid] > nums[mid + 1]) {
end = mid;
}
// 不存在相等的点;否则二分法不能做
}
return Math.max(nums[start], nums[end]);
}
}
方法2
// version 2: 一个比较啰嗦的版本,本质也是2分法,每次取两个点
public class Solution {
/**
* @param nums a mountain sequence which increase firstly and then decrease
* @return then mountain top
*/
public int mountainSequence(int[] nums) {
int left = 0, right = nums.length - 1;
while (left + 1 < right) {
int m1 = left + (right - left) / 2;
int m2 = right - (right - m1) / 2;
if (nums[m1] < nums[m2]) {
left = m1 + 1;
} else if (nums[m1] > nums[m2]) {
right = m2 - 1;
} else {
left = m1;
right = m2;
}
}
return nums[left] > nums[right] ? nums[left] : nums[right];
}
}