你的位置:首页 > 软件开发 > Java > [LeetCode] Find Peak Element

[LeetCode] Find Peak Element

发布时间:2015-08-15 18:00:20
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 a ...

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;  }}

原标题:[LeetCode] Find Peak Element

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录