# Leetcode 162. Find Peak Element

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

• 本文已收录于以下专栏：

举报原因： 您举报文章：Leetcode 162. Find Peak Element 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)