Topic describes

A peak element is an element whose value is greater than its left and right neighbors. // Given an input array nums, find the peak element and return its index. The array may contain multiple peaks, in which case any one of the peaks is returned. // You can assume that nums[-1] = nums[n] = -∞.Copy the code

Answer key

Nums [I], nums[I + 1], nums[I + 1], nums[I + 1] If nums[I] and nums[I + 1] // are found in descending order, the nums[I] encountered is peak. If the descending part is not traversed, nums // is always in ascending order, and the last element is the peak, which is why we initialize res to nums. length-1 // and return res directly. // // execution time: 0 ms, beat 100.00% user // memory consumption in all Java commits: Class Solution {public int findPeakElement(int[] nums) {int res = nums.length - 1; for (int i = 0; i < nums.length - 1; i++) { if (nums[i] > nums[i + 1]) { res = i; break; } } return res; }}Copy the code
Nums [mid] and nums[mid + 1] are not in descending order. If nums[mid] and nums[mid + 1] are not in descending order, the peak value is at the right of mid. // set l to mid+1. If it is in descending order, it indicates that the peak value is on the left, and the right pointer R moves left to mid position //. When the left and right Pointers meet, it indicates that the peak value is encountered, and the position where the left and right Pointers meet is returned. // // execution time: 0 ms, beat 100.00% user // memory consumption in all Java commits: Class Solution {public int findPeakElement(int[] nums) {int l = 0, r = nums.length - 1; while (l < r) { int mid = (l + r) / 2; if (nums[mid] <= nums[mid + 1]) l = mid + 1; else r = mid; } return l; }}Copy the code