【Likou】162. Looking for the Peak<Dichotomy>

【Likou】162. Looking for the Peak

A peak element is one whose value is strictly greater than its left and right neighbors.
Given an integer array nums, find the peak element and return its index. The array may contain multiple peaks, in which case it is sufficient to return the location of any one of the peaks.
You can assume nums[-1] = nums[n] = -∞.
You have to implement an algorithm with time complexity O(log n) to solve this problem.

Example 1:
Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is the peak element and your function should return its index 2.

Example 2:
Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return index 1, whose peak element is 2; or return index 5, whose peak The element is 6.

提示:
1 <= nums.length <= 1000
- 2 31 2^{31} 231 <= nums[i] <= 2 31 2^{31} 231 - 1
has nums[i] != nums[i + 1] for all valid i

answer

Dichotomy improvement (no sorting required): no matter what, there is a peak element.
Return the position of any peak: just find the local peak.

public class Solution {
    
    
    public int findPeakElement(int[] nums) {
    
    
        if (nums == null || nums.length == 0) {
    
    
            return -1;
        }

        int left = 0;
        int right = nums.length - 1;

        while (left < right) {
    
    
            int mid = left + (right - left) / 2;

			//mid左边肯定存在峰值
            if (nums[mid] > nums[mid + 1]) {
    
    
                right = mid;
            }
            //mid右边肯定存在峰值
            else {
    
    
                left = mid + 1;
            }
        }
        return left;
    }
}

Guess you like

Origin blog.csdn.net/qq_44033208/article/details/131880258