Skip to content

Commit 1215ac1

Browse files
committed
Sync LeetCode submission Runtime - 0 ms (100.00%), Memory - 17.9 MB (5.19%)
1 parent b4440d3 commit 1215ac1

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

0162-find-peak-element/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<p>A peak element is an element that is strictly greater than its neighbors.</p>
2+
3+
<p>Given a <strong>0-indexed</strong> integer array <code>nums</code>, find a peak element, and return its index. If the array contains multiple peaks, return the index to <strong>any of the peaks</strong>.</p>
4+
5+
<p>You may imagine that <code>nums[-1] = nums[n] = -&infin;</code>. In other words, an element is always considered to be strictly greater than a neighbor that is outside the array.</p>
6+
7+
<p>You must write an algorithm that runs in <code>O(log n)</code> time.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
12+
<pre>
13+
<strong>Input:</strong> nums = [1,2,3,1]
14+
<strong>Output:</strong> 2
15+
<strong>Explanation:</strong> 3 is a peak element and your function should return the index number 2.</pre>
16+
17+
<p><strong class="example">Example 2:</strong></p>
18+
19+
<pre>
20+
<strong>Input:</strong> nums = [1,2,1,3,5,6,4]
21+
<strong>Output:</strong> 5
22+
<strong>Explanation:</strong> Your function can return either index number 1 where the peak element is 2, or index number 5 where the peak element is 6.</pre>
23+
24+
<p>&nbsp;</p>
25+
<p><strong>Constraints:</strong></p>
26+
27+
<ul>
28+
<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
29+
<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
30+
<li><code>nums[i] != nums[i + 1]</code> for all valid <code>i</code>.</li>
31+
</ul>

0162-find-peak-element/solution.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Approach 3: Iterative Binary Search
2+
3+
# Time: O(log n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def findPeakElement(self, nums: List[int]) -> int:
8+
l, r = 0, len(nums) - 1
9+
10+
while l < r:
11+
mid = (l + r) // 2
12+
if nums[mid] > nums[mid + 1]:
13+
r = mid
14+
else:
15+
l = mid + 1
16+
17+
return l

0 commit comments

Comments
 (0)