【二分查找】LeetCode 162. 寻找峰值思路

题目链接

162. 寻找峰值思路

思路

一个不严谨但是好理解的思路是:如果 \(nums[mid] > nums[mid + 1]\),那么 \(nums[mid + 1]\) 肯定不是峰值,此时让 \(right = mid\),从左边继续找峰值。反之则 \(nums[mid]\) 肯定不为峰值,让 \(left = mid + 1\)

代码

class Solution {
    public int findPeakElement(int[] nums) {
        int n = nums.length;
        int left = 0;
        int right = n - 1;
        while(left < right){
            int mid = (right - left) / 2 + left;
            if(nums[mid] > nums[mid + 1]){
                right = mid;
            }else{
                left = mid + 1;
            }
        }

        return left;
    }
}
posted @ 2023-05-13 09:54  Frodo1124  阅读(36)  评论(0编辑  收藏  举报