当前位置:网站首页>LeetCode:162. Looking for peak

LeetCode:162. Looking for peak

2022-07-06 08:51:00 Bertil

The peak element refers to the element whose value is strictly greater than the left and right adjacent values .

Give you an array of integers nums, Find the peak element and return its index . The array may contain multiple peaks , under these circumstances , return Any peak Just where you are .

You can assume nums[-1] = nums[n] = -∞ .

You must achieve a time complexity of O(log n) Algorithm to solve this problem .

Example 1:

 Input :nums = [1,2,3,1]
 Output :2
 explain :3  Is the peak element , Your function should return its index  2.

Example 2:

 Input :nums = [1,2,1,3,5,6,4]
 Output :1  or  5 
 explain : Your function can return the index  1, Its peak element is  2;
      Or return index  5,  Its peak element is  6.

Tips :

  • 1 <= nums.length <= 1000
  • -2^31 <= nums[i] <= 2^31 - 1
  • For all that works i There are nums[i] != nums[i + 1]

Their thinking

1. First, find the largest element , Then return to its index
2. explain : Why is the maximum the answer ?

  • Because the title has assumed nums[-1] = nums[n] = -∞, So the peak will not appear in the first and last elements
  • The left and right adjacent elements of the maximum value in the array must be less than the maximum value

Code

/** * @param {number[]} nums * @return {number} */
var findPeakElement = function(nums) {
    
    return nums.indexOf(Math.max(...nums))
};
原网站

版权声明
本文为[Bertil]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060844308456.html