[LeetCode] 162. Find Peak Element
求数组的局部峰值。给一个数组,数组满足条件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)
/** * @param {number[]} nums * @return {number} */ var findPeakElement = function(nums) { let start = 0; let end = nums.length - 1; while (start + 1 < end) { let mid = Math.floor(start + (end - start) / 2); if (nums[mid] > nums[mid + 1]) { end = mid; } else { start = mid; } } if (nums[start] > nums[end]) return start; return end; };
相关推荐
wikiwater 2020-10-27
IdeaElements 2020-08-19
Sophiego 2020-08-16
Kakoola 2020-08-01
Kakoola 2020-07-29
ELEMENTS爱乐冬雨 2020-07-18
ELEMENTS爱乐小超 2020-07-04
ELEMENTS爱乐小超 2020-07-04
Kakoola 2020-06-28
Feastaw 2020-06-18
Wmeng0 2020-06-14
ELEMENTS爱乐冬雨 2020-06-14
云之高水之远 2020-06-14
哈喽elements 2020-06-14
Feastaw 2020-06-11