# 162.Find Peak Element

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

Given an input array nums, where nums[i] ≠ nums[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 nums[-1] = nums[n] = -∞.

Example 1:

Input: nums = [1,2,3,1]
Output: 2
Explanation: 3 is a peak element and your function should return the index number 2.
Example 2:

Input: nums = [1,2,1,3,5,6,4]
Output: 1 or 5
Explanation: Your function can return either index number 1 where the peak element is 2,
or index number 5 where the peak element is 6.

Note:
Your solution should be in logarithmic complexity.```

```This problem is similar to Local Minimum. And according to the given condition,
num[i] != num[i+1], there must exist a O(logN) solution. So we use binary search for this problem.
If num[i-1] < num[i] > num[i+1], then num[i] is peak
If num[i-1] < num[i] < num[i+1], then num[i+1...n-1] must contains a peak
If num[i-1] > num[i] > num[i+1], then num[0...i-1] must contains a peak
If num[i-1] > num[i] < num[i+1], then both sides have peak
(n is num.length)```

```   public int findPeakElement(int[] nums) {
int left = 1,right = nums.length-2;
int mid = 0;
if (nums.length==1|| nums[1]< nums[0]) return 0;
if (nums[nums.length-2]<nums[nums.length-1]) return nums.length-1;
while (left <= right){
mid = left+(right -left)/2;
if (nums[mid]>nums[mid+1]&& nums[mid]>nums[mid-1]) return mid;
else if (nums[mid]>nums[mid+1]&& nums[mid]<nums[mid-1]) right = mid-1;
else if (nums[mid]<nums[mid+1]&& nums[mid]>nums[mid-1]) left = mid+1;
else right = mid-1;
}
return -1;
}```

0 条评论

## 相关文章

3778

### Java中net.sf.json包关于JSON与对象互转的坑

在Web开发过程中离不开数据的交互，这就需要规定交互数据的相关格式，以便数据在客户端与服务器之间进行传递。数据的格式通常有2种：1、xml；2、JSON。通...

3855

48510

2495

### 浅谈C/C++中的指针和数组（一）

浅谈C/C++中的指针和数组（一）       指...

2235

### 谈谈fail-fast与fail-safe

fail-fast的字面意思是“快速失败”。当我们在遍历集合元素的时候，经常会使用迭代器，但在迭代器遍历元素的过程中，如果集合的结构被改变的话，就会抛出异常，防...

1324

3798

1637

3697

1634