星空网 > 软件开发 > Java

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

 




原标题:[LeetCode] Find Peak Element

关键词:

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

跨境ChatGPT,永久免费使用!抓紧注册!:https://www.kjdsnews.com/a/1452217.html
菜鸟集团启动上市计划;华贸物流拟成立新合资公司:https://www.kjdsnews.com/a/1452218.html
亚马逊CPC产品认证详解:https://www.kjdsnews.com/a/1452219.html
如何利用ChatGPT帮助亚马逊运营?:https://www.kjdsnews.com/a/1452220.html
单价仅0.06美元的透明磨砂中性笔卖到了2.3M件丨tiktok数据分析超店有数:https://www.kjdsnews.com/a/1452221.html
美国首例!宣布全面封杀TikTok!违者每天罚款7万:https://www.kjdsnews.com/a/1452222.html
去日本入住酒店,东西随意用却有一个特殊“要:https://www.vstour.cn/a/411241.html
中国有哪些著名的酒店品牌。:https://www.vstour.cn/a/411242.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流