题目描述
符合下列属性的数组 arr 称为 山峰数组(山脉数组) :
arr.length >= 3
存在 i(0 < i < arr.length - 1)使得:
arr[0] < arr[1] < ... arr[i-1] < arr[i]
arr[i] > arr[i+1] > ... > arr[arr.length - 1]
给定由整数组成的山峰数组 arr ,返回任何满足 arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1] 的下标 i ,即山峰顶部。
示例 1:
输入:arr = [0,1,0]
输出:1
示例 2:
输入:arr = [1,3,5,4,2]
输出:2
示例 3:
输入:arr = [0,10,5,2]
输出:1
示例 4:
输入:arr = [3,4,5,1]
输出:2
示例 5:
输入:arr = [24,69,100,99,79,78,67,36,26,19]
输出:2
提示:
3 <= arr.length <= 10^4
0 <= arr[i] <= 106
题目数据保证 arr 是一个山脉数组
进阶:很容易想到时间复杂度 O(n) 的解决方案,你可以设计一个 O(log(n)) 的解决方案吗?
暴力 o(n)
//找最大值即可
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int res = 0;
int min = arr[0];
for (int i = 1; i < arr.length - 1; i++) {
if(arr[i] > min){
res = i;
min = arr[i];
}
}
return res;
}
}
寻找递增数组右边界
可以发现,山脉数组的特征是左边是一个递增数组,右边是一个递减数组,我们的目标是寻找左边递增数组的右边界即可
情况一:1 2 3 4 5 6 7 1
情况二:1 2 3 4 5 6 9 8
情况三:1 7 6 5 4 3 2 1
class Solution {
public static int peakIndexInMountainArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
int mid;
while (left < right) {
mid = ((right - left + 1) >> 1) + left;
//寻找递增数组
if (arr[mid] < arr[right] || arr[mid - 1] < arr[mid]) {
left = mid;
} else {
//递增数组右边界
right = mid - 1;
}
}
return right;
}
}
寻找递减数组左边界
class Solution {
public static int peakIndexInMountainArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
int mid;
while (left < right) {
mid = ((right - left) >> 1) + left;
//寻找递减数组
if (arr[mid] > arr[right] && arr[mid - 1] > arr[mid]) {
right = mid;
} else {
//递减数组左边界,加1 可能导致左边界往后推移一位
left = mid + 1;
}
}
return arr[right - 1] > arr[right]?right -1 : right;
}
}
仔细想一想,为什么要用arr[right] 和arr[mid]比较呢?山脉数组的特征是相邻节点之间的关系
寻找递减左边界
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int n = arr.length;
int left = 1, right = n - 2;
while (left < right) {
int mid = (left + right) / 2;
if (arr[mid] > arr[mid + 1]) {
right = mid;
} else {
left = mid + 1;
}
}
return right;
}
}
寻找递增右边界
class Solution {
public int peakIndexInMountainArray(int[] arr) {
int n = arr.length;
int left = 1, right = n - 2;
while (left < right) {
int mid = (left + right + 1) / 2;
if (arr[mid - 1] < arr[mid]) {
left = mid;
} else {
right = mid - 1;
}
}
return right;
}
}