[LeetCode] 162. Find Peak Element
Posted aaronliu1991
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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)
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的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 162 Find Peak Element(二分法)
刷题-LeetCode162 Find Peak Element
LeetCode 162. Find Peak Element 20170706