[leetcode]162. Find Peak Element

[leetcode]162. Find Peak Element


Analysis

missing—— [每天刷题并不难0.0]

A peak element is an element that is greater than its neighbors.
Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that nums[-1] = nums[n] = -∞.
[leetcode]162. Find Peak Element

Explanation:

Using binary search or sequential search

Implement

Binary Search

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

Sequential Search

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        int len = nums.size();
        for(int i=1; i<len; i++){
            if(nums[i-1]>nums[i])
                return i-1;
        }
        return len-1;
    }
};