File tree Expand file tree Collapse file tree 2 files changed +46
-1
lines changed
LeetCodeSolutions/BinarySearch Expand file tree Collapse file tree 2 files changed +46
-1
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -176,7 +176,7 @@ The Top Interview 150 collection on Leetcode is a curated set of 150 interview q
176
176
| <br > Binary Search<br > | | | |
177
177
| 114 | Search Insert Position | Easy | ✅ |
178
178
| 115 | Search a 2D Matrix | Medium | |
179
- | 116 | Find Peak Element | Medium | |
179
+ | 116 | Find Peak Element | Medium | ✅ |
180
180
| 117 | Search in Rotated Sorted Array | Medium | |
181
181
| 118 | Find First and Last Position of Element in Sorted Array | Medium | |
182
182
| 119 | Find Minimum in Rotated Sorted Array | Medium | |
You can’t perform that action at this time.
0 commit comments