Leetcode 162 Find Peak Element

给定一个数组,找到山峰元素
https://leetcode.com/problems/find-peak-element/description/

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

解答:
这道题本质上是从左到右,找到最后一个大于左边元素的位置,那就可以二分作答了。注意要判断一下mid是否大于0。如果不判也是对的,但是这是因为模版 r − l + 1 r - l +1 rl+1带来的好处,恰好能处理所有的特殊情况。
为了防止数组越界,添加mid > 0 更安全

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int l = 0;
        int r = nums.size() - 1;
        while ( l < r ) {
            int mid = l + ( r - l ) + 1 / 2;
            if( mid > 0) {
                if( nums[mid] > nums[mid - 1]) {
                    l = mid;
                } else {
                    r = mid - 1;
                }
            } else {
                return mid;
            }
        }
        return l;
    }
};

算法复杂度 O ( l o g n ) O(logn) O(logn)
空间复杂度 O ( 1 ) O(1) O(1)

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