Skip to content

Commit 69cf8a1

Browse files
committed
https://leetcode.com/problems/find-peak-element/
1 parent 28e6f27 commit 69cf8a1

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
namespace LeetCodeSolutions.BinarySearch;
2+
3+
public class FindPeakElementSolution
4+
{
5+
public int FindPeakElement(int[] nums) {
6+
int left = 0;
7+
int right = nums.Length - 1;
8+
9+
// Binary search for a peak
10+
while (left < right) {
11+
int mid = left + (right - left) / 2;
12+
13+
// If the current mid is greater than its right neighbor,
14+
// then the peak must be on the left side (including mid)
15+
if (nums[mid] > nums[mid + 1]) {
16+
right = mid;
17+
} else {
18+
// Otherwise, the peak is on the right side (excluding mid)
19+
left = mid + 1;
20+
}
21+
}
22+
23+
// When left == right, we've found a peak
24+
return left;
25+
}
26+
27+
[Test(Description = "https://leetcode.com/problems/find-peak-element/")]
28+
[Category("Medium")]
29+
[Category("LeetCode")]
30+
[Category("Find Peak Element")]
31+
[TestCaseSource(nameof(Input))]
32+
[Category("BinarySearch")]
33+
[Category("TopInterview")]
34+
public void Test1((int Output, int[] Input) item)
35+
{
36+
var response = FindPeakElement(item.Input);
37+
Assert.That(response, Is.EqualTo(item.Output));
38+
}
39+
40+
public static IEnumerable<(int Output, int[] Input)> Input =>
41+
new List<(int Output, int[] Input)>()
42+
{
43+
(5, [1,2,1,3,5,6,4]),
44+
};
45+
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ The Top Interview 150 collection on Leetcode is a curated set of 150 interview q
176176
| <br> Binary Search<br> | | | |
177177
| 114 | Search Insert Position | Easy ||
178178
| 115 | Search a 2D Matrix | Medium | |
179-
| 116 | Find Peak Element | Medium | |
179+
| 116 | Find Peak Element | Medium | |
180180
| 117 | Search in Rotated Sorted Array | Medium | |
181181
| 118 | Find First and Last Position of Element in Sorted Array | Medium | |
182182
| 119 | Find Minimum in Rotated Sorted Array | Medium | |

0 commit comments

Comments
 (0)