162. Find Peak Element

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.

【思路】顺序查找,依次检查每个元素,直到有符合要求的返回。

class Solution {
public:
    int findPeakElement(vector<int>& nums) {
        if(nums.size()<=1) return 0;
        int root, left, right;
        int len = nums.size();
        int i = 1;
        root = nums[0];
        while(i<len)
        {
            if(nums[i] > root)
            {
                left = root;
                root = nums[i];
                if((i!= len-1) && (nums[i+1]<root))
                 return i;
                if(i==len-1)
                 return i;
            }
            if(nums[i] < root)
            {
                right = nums[i];
                return i-1;
            }
            i++;
        }
    }
};



你可能感兴趣的:(162. Find Peak Element)