首页 > 学院 > 开发设计 > 正文

[LeetCode] Find Peak Element

2019-11-15 01:08:39
字体:
来源:转载
供稿:网友
[LeetCode] Find Peak Element

A peak element is an element that is greater than its neighbors.

Given an input array wherenum[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 thatnum[-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;    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表