LeetCode OJ: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.

感觉不太像medium的题目,但是我写的比价乱啊,代码如下:

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

java代码:

public class Solution {
    public int findPeakElement(int[] nums) {
        if(nums.length == 0 || nums.length == 1)
            return 0;
        if(nums[0] > nums[1])
            return 0;
        for(int i = 1; i < nums.length; ++i){
            if(nums[i] > nums[i - 1]){
                if(i+1 >= nums.length || nums[i] > nums[i+1])
                    return i;
            }
        }
        return nums.length - 1;
    }
}

 

posted @ 2015-11-03 15:19  eversliver  阅读(271)  评论(0编辑  收藏  举报