爱程序网

[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.

     这道题没啥可说的。用loop来循环比较就可以了。

     只是需要注意,题目中说了不考虑第一个数为peak element,但是对于最后一个数,只要这个数大于了前面的那个数,它就可以算作是peak element。

     代码如下。~

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

 

关于爱程序网 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助