乐趣区

9 .leetcode Peak Index in a Mountain Array

1 题目
Let’s call an array A a mountain if the following properties hold:
A.length >= 3There exists some 0 < i < A.length – 1 such that A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length – 1]Given an array that is definitely a mountain, return any i such that A[0] < A[1] < … A[i-1] < A[i] > A[i+1] > … > A[A.length – 1].
例子
Input: [0,1,0]
Output: 1
Input: [0,2,1,0]
Output: 1
我的解法
var peakIndexInMountainArray = function(A) {
let i = 0
while (i < A.length){
if (A[i] > A[i+1]){
break
}
i++
}
return i
};
Runtime: 60 ms, faster than 85.20% of JavaScript online submissions for Peak Index in a Mountain Array.Memory Usage: 35 MB, less than 52.70% of JavaScript online submissions for Peak Index in a Mountain Array.
其他解法
var peakIndexInMountainArray = function(A) {
return A.indexOf(Math.max(…A));
};
求最大值然后求 index
var peakIndexInMountainArray = function(A) {
function mid(a,b) {
return Math.floor((b-a)/2);
}

let left = 0, right = A.length-1;
let pivot = mid(left, right);

while (A[pivot-1]>A[pivot] || A[pivot]<A[pivot+1] ) {
if(A[pivot]>A[pivot+1]) {
right = pivot;
pivot = mid(left, right)
} else {
left = pivot;
pivot += mid(left, right)
}
}

return pivot;
};
二分法查找

退出移动版