0
点赞
收藏
分享

微信扫一扫

Leetcode162. 寻找峰值


题目传送:​​https://leetcode.cn/problems/find-peak-element/submissions/​​

运行效率

Leetcode162. 寻找峰值_leetcode


代码如下:

public int findPeakElement(int[] nums) {
//处理边界情况
if (nums.length == 1) {
return 0;
}
if (nums.length == 2) {
return nums[0] > nums[1] ? 0 : 1;
}
int left = 0;
int mid = 1;
int right = 2;
while (right < nums.length) {
//处理特殊边界
if(left==0){
//比如[3,2,1] 就应该返回0号位置的索引
if(nums[left]>nums[mid]){
return 0;
}
}
if(right== nums.length-1){
if(nums[right]>nums[mid]){
return nums.length-1;
}
}

if (nums[left] < nums[mid] && nums[mid] > nums[right]) {
return mid;
}
left++;
mid++;
right++;
}
return -1;

}


举报

相关推荐

0 条评论