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题。题目说的很绕,其实是给了一个数组,其中只有一个峰值,峰值左半边递增,右半边递减,请你找出这个峰值。
两种思路,一种是线性找,找if (nums[i] > nums[i - 1]),一种是二分法。我这里给出二分法的代码。
时间O(logn)
空间O(1)
Java实现
1 class Solution { 2 public int peakIndexInMountainArray(int[] arr) { 3 int left = 0; 4 int right = arr.length - 1; 5 while (left < right) { 6 int mid = left + (right - left) / 2; 7 if (arr[mid] < arr[mid + 1]) { 8 left = mid + 1; 9 } else { 10 right = mid; 11 } 12 } 13 return left; 14 } 15 }
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 };