[LeetCode] 852. Peak Index in a Mountain Array
Let's call an array arr
a mountain if the following properties hold:
arr.length >= 3
- There exists some
i
with0 < i < arr.length - 1
such that:arr[0] < arr[1] < ... arr[i-1] < arr[i]
arr[i] > arr[i+1] > ... > arr[arr.length - 1]
Given an integer array arr
that is guaranteed to be a mountain, return any i
such that arr[0] < arr[1] < ... arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
.
Example 1:
Input: arr = [0,1,0] Output: 1
Example 2:
Input: arr = [0,2,1,0] Output: 1
Example 3:
Input: arr = [0,10,5,2] Output: 1
Example 4:
Input: arr = [3,4,5,1] Output: 2
Example 5:
Input: arr = [24,69,100,99,79,78,67,36,26,19] Output: 2
Constraints:
3 <= arr.length <= 104
0 <= arr[i] <= 106
arr
is guaranteed to be a mountain array.
Follow up: Finding the O(n)
is straightforward, could you find an O(log(n))
solution?
山脉数组的峰顶索引。
符合下列属性的数组 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 。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/peak-index-in-a-mountain-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
影子题162。这个题还有一个followup,1095题。题目说的很绕,其实是给了一个数组,其中一定存在一个峰值,峰值左半边递增,右半边递减,请你找出这个峰值。
这个题面试的时候一定要求用二分法解决。因为找的是数组里的峰值,所以我用的是左闭右开的模板,其他部分参见代码注释。
时间O(logn)
空间O(1)
Java实现
1 class Solution { 2 public int peakIndexInMountainArray(int[] arr) { 3 int start = 0; 4 int end = arr.length; 5 // 左闭右开 6 while (start < end) { 7 int mid = start + (end - start) / 2; 8 // 因为mid一定不是峰值,所以搜索区间变为[mid, right) 9 if (arr[mid] < arr[mid + 1]) { 10 start = mid + 1; 11 } 12 // 有可能mid是峰值,所以搜索区间变为[start, end) 13 else { 14 end = mid; 15 } 16 } 17 return start; 18 } 19 }
JavaScript实现
1 var peakIndexInMountainArray = function (arr) { 2 let left = 0; 3 let right = arr.length; 4 while (left < right) { 5 let mid = Math.floor(left + (right - left) / 2); 6 if (arr[mid] < arr[mid + 1]) { 7 left = mid + 1; 8 } else { 9 right = mid; 10 } 11 } 12 return left; 13 };