[LeetCode] 162. Find Peak Element

拜拜、爱过 提交于 2019-12-03 10:38:04

求数组的局部峰值。给一个数组,数组满足条件nums[i] ≠ nums[i+1],求数组峰值的下标。例子

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.

Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5 
Explanation: Your function can return either index number 1 where the peak element is 2, 
             or index number 5 where the peak element is 6.

思路是用二分法,因为题目要求时间复杂度是log级别。

时间O(logn)

空间O(1)

 1 /**
 2  * @param {number[]} nums
 3  * @return {number}
 4  */
 5 var findPeakElement = function(nums) {
 6     let start = 0;
 7     let end = nums.length - 1;
 8     while (start + 1 < end) {
 9         let mid = Math.floor(start + (end - start) / 2);
10         if (nums[mid] > nums[mid + 1]) {
11             end = mid;
12         } else {
13             start = mid;
14         }
15     }
16     if (nums[start] > nums[end]) return start;
17     return end;
18 };

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!