forked from leetcoders/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindPeakElement.java
executable file
·30 lines (29 loc) · 1.05 KB
/
FindPeakElement.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/*
Author: King, [email protected]
Date: Dec 06, 2014
Problem: Find Peak Element
Difficulty: Medium
Source: https://oj.leetcode.com/problems/find-peak-element/
Notes:
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.
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.
Find the peak element.
*/
public class Solution {
public int findPeakElement(int[] num) {
int left = 0, right = num.length - 1, mid = -1;
while (left <= right) {
mid = (left + right) /2;
if ((mid == 0 || num[mid-1] <= num[mid]) && (mid == num.length - 1 || num[mid] >= num[mid+1]))
return mid;
if (mid > 0 && num[mid-1] > num[mid]) {
right = mid - 1;
} else if (num[mid+1] > num[mid]) {
left = mid + 1;
}
}
return mid;
}
}