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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

 

 1 class Solution {
 2 public:
 3     int findPeakElement(vector<int>& nums) {
 4         if(nums.size()==0) return NULL;
 5 
 6         for(int i=1;i<nums.size();i++)
 7         {
 8             if(nums[0]>nums[1])
 9                 return 0;
10             if(nums[nums.size()-1]>nums[nums.size()-2])
11                 return nums.size()-1;
12             if(nums[i]>nums[i-1]&&nums[i]>nums[i+1])
13                 return i;
14 
15         }
16 
17         return NULL;
18     }
19 };

 

posted on 2015-05-05 08:46  黄瓜小肥皂  阅读(137)  评论(0编辑  收藏  举报