leetcode 题目: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.


思路:如果中间元素小于其后相邻元素,则右侧必有一个局部最大值,如果中间元素小于前一个,则左侧必有局部最大值.

    int findPeakElement(vector<int>& nums) {
        int left,right,mid;
        left =0;
        right = nums.size()-1;
        
        if(nums.size()<3)
        {
            if(nums.size()==1)
                return 0;
            else
                return nums[0]>nums[1] ? 0:1;
        }
        
        
        while(right>left)
        {
            mid = left + (right - left)/2;
            
            
            if((nums[mid]>nums[mid-1]) && (nums[mid]>nums[mid+1]))
            {
                return mid;
            }
            
            if(nums[mid]>nums[mid-1])
            {
                left = mid;
            }
            else 
            {
                right = mid -1;
            }
            
            
        }
        
        return nums[0]>nums[nums.size()-1] ? 0:nums.size()-1;
        
    }

猜你喜欢

转载自blog.csdn.net/u013721521/article/details/79764303