Skip to content

Commit d8d61f5

Browse files
committed
solve 162.find-peak-element
1 parent 1cab136 commit d8d61f5

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

vscode/162.find-peak-element.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
* @lc app=leetcode id=162 lang=java
3+
*
4+
* [162] Find Peak Element
5+
*
6+
* https://leetcode.com/problems/find-peak-element/description/
7+
*
8+
* algorithms
9+
* Medium (41.71%)
10+
* Likes: 965
11+
* Dislikes: 1468
12+
* Total Accepted: 260.6K
13+
* Total Submissions: 624.7K
14+
* Testcase Example: '[1,2,3,1]'
15+
*
16+
* A peak element is an element that is greater than its neighbors.
17+
*
18+
* Given an input array nums, where nums[i] ≠ nums[i+1], find a peak element
19+
* and return its index.
20+
*
21+
* The array may contain multiple peaks, in that case return the index to any
22+
* one of the peaks is fine.
23+
*
24+
* You may imagine that nums[-1] = nums[n] = -∞.
25+
*
26+
* Example 1:
27+
*
28+
*
29+
* Input: nums = [1,2,3,1]
30+
* Output: 2
31+
* Explanation: 3 is a peak element and your function should return the index
32+
* number 2.
33+
*
34+
* Example 2:
35+
*
36+
*
37+
* Input: nums = [1,2,1,3,5,6,4]
38+
* Output: 1 or 5
39+
* Explanation: Your function can return either index number 1 where the peak
40+
* element is 2,
41+
* or index number 5 where the peak element is 6.
42+
*
43+
*
44+
* Note:
45+
*
46+
* Your solution should be in logarithmic complexity.
47+
*
48+
*/
49+
class Solution {
50+
public int findPeakElement(int[] nums) {
51+
int low = 0;
52+
int high = nums.length - 1;
53+
while (low < high) {
54+
int mid1 = low + (high - low) / 2;
55+
int mid2 = mid1 + 1;
56+
if (nums[mid1] < nums[mid2]) {
57+
low = mid2;
58+
} else {
59+
high = mid1;
60+
}
61+
}
62+
return low;
63+
}
64+
}
65+

0 commit comments

Comments
 (0)