# Leetcode 162. Find Peak Element

116人阅读 评论(0)

### 162. Find Peak Element

Total Accepted: 78108 Total Submissions: 227653 Difficulty: Medium

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.

click to show spoilers.

Note:

Your solution should be in logarithmic complexity.

public class Solution {
public int findPeakElement(int[] nums) {
if(nums.length == 1) return 0;

int peak = Integer.MIN_VALUE, index = -1, last = nums.length - 1;
if(nums[0] > nums[1]) { index = 0; peak = nums[0]; }
if(nums[last] > nums[last-1] && nums[last] > peak) { index = last; peak = nums[last]; }

for(int i = 1; i <= last-1; i++){
if(nums[i-1] < nums[i] && nums[i] > nums[i+1]){
if(nums[i] > peak){
index = i; peak = nums[i];
}
}
}
return index;
}
}

public class Solution {
public int findPeakElement(int[] nums) {
int len = nums.length;
if (len == 1) return 0;
int start = 0;
int end = len -1;
int res = 0;
if (nums[start]>nums[start+1]) return 0; // according to nums[-1] = nums[n] = -∞,
if (nums[end]>nums[end-1]) return end;// so return start or end if one of them is greater than its neighbor.
while (start<end) {
int mid = (start + end)/2;
if (nums[mid]>nums[mid+1] && nums[mid]>nums[mid-1]) { //mid is greater than its neighbors
res = mid;
break;
}else if (nums[mid]<nums[mid+1]) {
start = mid;
}else {
end = mid;
}
}
return res;
}
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：32252次
• 积分：1612
• 等级：
• 排名：千里之外
• 原创：133篇
• 转载：3篇
• 译文：0篇
• 评论：22条
文章分类
最新评论