标签:
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[n] = -∞
.
For example, in array [1, 2, 3, 1]
, 3 is a peak element and your function should return the index number 2.
Your solution should be in logarithmic complexity.
https://leetcode.com/problems/find-peak-element/
提示说要求指数级的复杂度,我就想不能够吧...
原来是先入为主了,没说求最高的峰顶,只要是峰顶,随便哪个都可以Orz。
我原以为是有多个最高的峰顶,输出哪个都可以,原来要求这么随便,这样真的没问题吗。
于是就可以二分了,中点无非就是四种情况。
1.中点是峰顶,直接输出,收工。
2.中点在一条上坡里,峰顶肯定在右边。
3.中点在一条下坡里,峰顶肯定在左边。
4.中点是峰谷,取左边和右边都可以...
1 /** 2 * @param {number[]} nums 3 * @return {number} 4 */ 5 var findPeakElement = function(nums) { 6 var m = 0, n = nums.length - 1; 7 var middle, left, right; 8 while(m <= n){ 9 middle = parseInt((m + n) / 2); 10 left = nums[middle - 1] ? nums[middle - 1] : -Infinity; 11 right = nums[middle + 1] ? nums[middle + 1] : -Infinity; 12 if(nums[middle] > left && nums[middle] > right){ 13 return middle; 14 }else if(left < nums[middle]&& nums[middle] < right){ 15 m = middle + 1; 16 }else{ 17 n = middle - 1; 18 } 19 } 20 return nums[m] > nums[n] ? nums[m] : nums[n]; 21 };
[LeetCode][JavaScript]Find Peak Element
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/4614878.html