码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 162. Find Peak Element

时间:2019-11-04 13:51:26      阅读:77      评论:0      收藏:0      [点我收藏+]

标签:floor   bsp   复杂度   should   题目   Plan   NPU   where   xpl   

求数组的局部峰值。给一个数组,数组满足条件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 };

 

[LeetCode] 162. Find Peak Element

标签:floor   bsp   复杂度   should   题目   Plan   NPU   where   xpl   

原文地址:https://www.cnblogs.com/aaronliu1991/p/11791474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!