[Leetcode]Find Peak Element

来源:互联网 发布:centos 删除 rm 编辑:程序博客网 时间:2024/06/08 11:15

A peak element is an element that is greater than its neighbors.

Given an input array where num[i] ≠ num[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 num[-1] = num[n] = -∞.

For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

class Solution {public:    /*algorithm : linear search        time O(n) space O(1)    */    int findPeakElement(vector<int>& nums) {        for(int i = 0;i < nums.size();i++){            bool prev = i==0?true:nums[i] > nums[i-1];            bool next = i+1==nums.size()?true:nums[i]>nums[i+1];            if(prev&&next)return i;        }        return -1;    }};

class Solution {public:    /*algorithm : linear search        time O(logn) space O(1)    */    int findPeakElement(vector<int>& nums) {//[0,1,2,3,1]        bool prev,next;        int l = 0,r = nums.size();        while(l < r){            int m = l + (r-l)/2;            prev = m == 0?true:nums[m] > nums[m-1];            next = m+1==nums.size()?true:nums[m] > nums[m+1];            if(prev&&next)return m;            else if(prev)l = m+1;            else r = m; //becasue [l,r),not [l,r]        }        return -1;    }};



0 0
原创粉丝点击