您的位置:首页 > Web前端 > JavaScript

[LeetCode][JavaScript]Find Peak Element

2015-07-01 23:43 856 查看

Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array where
num[i] ≠ num[i+1]
, find a peak element and return its index.

The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.

You may imagine that
num[-1] = num
= -∞
.

For example, in array
[1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.

click to show spoilers.

Note:
Your solution should be in logarithmic complexity.

https://leetcode.com/problems/find-peak-element/

提示说要求指数级的复杂度,我就想不能够吧...

原来是先入为主了,没说求最高的峰顶,只要是峰顶,随便哪个都可以Orz。

我原以为是有多个最高的峰顶,输出哪个都可以,原来要求这么随便,这样真的没问题吗。

于是就可以二分了,中点无非就是四种情况。

1.中点是峰顶,直接输出,收工。

2.中点在一条上坡里,峰顶肯定在右边。

3.中点在一条下坡里,峰顶肯定在左边。

4.中点是峰谷,取左边和右边都可以...

/**
* @param {number[]} nums
* @return {number}
*/
var findPeakElement = function(nums) {
var m = 0, n = nums.length - 1;
var middle, left, right;
while(m <= n){
middle = parseInt((m + n) / 2);
left = nums[middle - 1] ? nums[middle - 1] : -Infinity;
right = nums[middle + 1] ? nums[middle + 1] : -Infinity;
if(nums[middle] > left && nums[middle] > right){
return middle;
}else if(left < nums[middle]&& nums[middle] < right){
m = middle + 1;
}else{
n = middle - 1;
}
}
return nums[m] > nums
? nums[m] : nums
;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: