码迷,mamicode.com
首页 > 其他好文 > 详细

Find Peak Element

时间:2015-06-22 11:02:24      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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.

Code:

 1 //解法1:顺序查找
 2  int findPeakElement(vector<int>& nums) {
 3         size_t n = nums.size();
 4         assert (n!=0);
 5         
 6         if (n==1 || nums[0] > nums[1])
 7             return 0;
 8             
 9         if (nums[n-1] > nums[n-2])
10             return n-1;
11             
12         for (int i = 1; i <= n-2; ++i)
13         {
14             if (nums[i-1] < nums[i] && nums[i] > nums[i+1] )
15                 return i;
16         }
17         return -1;
18     }
//解法2:二分查找
int findPeakElement(vector<int>& nums) {
        int left = 0;
        int right = nums.size()-1;
        while (left < right)
        {
            int mid = (left + right)/2;
            if (nums[mid]<nums[mid+1])
                left = mid+1;//mid右边一定存在山峰
            else
                right = mid;//mid左边一定存在山峰
        }
        return left;
    }

 

 

Find Peak Element

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4592946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!