【leetcode】【二分查找】162. 寻找峰值

题目描述

162. 寻找峰值

解题思路

刷leetcode可以看答案,但是要有自己的思考。能够举一反三,就说明 有自己的思考。
二分法中,可以考虑的元素有 nums[left] nums[right] nums[mid] nums[mid±1]

解法1:nums[mid] ?= nums[mid+1]

在左闭右闭写法中。采用如下的二分区间选择算法。
nums[mid] > nums[mid+1] one peek must be in [left, mid]
nums[mid] < nums[mid+1] one peek must be in (mid, right]

解法2:nums[mid] ?= nums[right]

左闭右闭。采用如下的二分区间选择算法。
nums[mid] < nums[right] one peek must be in (mid, right]
nums[mid] > nums[right] one peek must be in can be none in [mid, right], can be none in [], must be in [left, mid]
nums[mid] == nums[right] one peek must be in none. [mid+1, right]
or [mid, right-1]
must be in [left, right-1]

class Solution {
public:
    int findPeakElement(vector& nums) {
        int n = nums.size();
        int left=0, right=n-1;
        while(leftnums[right]) {
                right = mid;    // [left, mid] must has one peek
            } else if (nums[mid]==nums[right]) {
                right--;            // [left, right-1] must has one peek
            }
        }
        return nums[left]>nums[left+1]?left:left+1;
    }
};

解法3:nums[mid] ?= nums[left]

左闭右闭。采用如下的二分区间选择算法。
nums[mid] < nums[left] one peek can be [left, mid-1]
nums[mid] > nums[left] one peek can be none in [left, mid], must be in [mid, right].
nums[mid] == nums[left] one peek must be in [mid+1, right]
or [mid, right-1]

你可能感兴趣的:(leecode,leetcode,二分查找)