Skip to content

Commit e84ba1e

Browse files
committed
[Medium] Title: 162. Find Peak Element - LeetCode
1 parent 5b8445f commit e84ba1e

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public int findPeakElement(int[] nums) {
3+
if (nums.length == 1) return 0;
4+
if (nums.length == 2) return nums[0] > nums[1] ? 0 : 1;
5+
6+
int startIdx = 0; int endIdx = nums.length - 1;
7+
8+
while(startIdx < endIdx) {
9+
10+
int midIdx = startIdx + (endIdx- startIdx) / 2;
11+
12+
if(nums[midIdx] < nums[midIdx + 1]) {
13+
startIdx = midIdx + 1;
14+
} else {
15+
endIdx = midIdx;
16+
}
17+
}
18+
return startIdx;
19+
}
20+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# [Medium] 162. Find Peak Element
2+
3+
[문제 링크](https://leetcode.com/problems/find-peak-element/)
4+
5+
### 문제 설명
6+
A peak element is an element that is strictly greater than its neighbors.
7+
8+
Given a**0-indexed**integer array`nums`, find a peak element, and return its index. If the array contains multiple peaks, return the index to**any of the peaks**.
9+
10+
You may imagine that`nums[-1] = nums[n] = -∞`. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.
11+
12+
You must write an algorithm that runs in`O(log n)`time.
13+
14+
**Example 1:**
15+
16+
```
17+
Input: nums = [1,2,3,1]
18+
Output: 2
19+
```
20+
21+
Explanation: 3 is a peak element and your function should return the index number 2.
22+
23+
**Example 2:**
24+
25+
```
26+
Input: nums = [1,2,1,3,5,6,4]
27+
Output: 5
28+
```
29+
30+
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.
31+
32+
**Constraints:**
33+
34+
- `1 <= nums.length <= 1000`
35+
- `231 <= nums[i] <= 231 - 1`
36+
- `nums[i] != nums[i + 1]`for all valid`i`.

0 commit comments

Comments
 (0)