Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9b86e98

Browse files
committed
"Find Peak Element"
1 parent 2d26b19 commit 9b86e98

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
138138
| 165 | [Compare Version Numbers] | [C](src/165.c) |
139139
| 164 | [Maximum Gap] | [C](src/164.c) |
140140
| 163 | [Missing Ranges]| |
141-
| 162 | [Find Peak Element] | |
141+
| 162 | [Find Peak Element] | [C](src/162.c) |
142142
| 161 | [One Edit Distance]| |
143143
| 160 | [Intersection of Two Linked Lists] | [C](src/160.c) |
144144
| 159 | [Longest Substring with At Most Two Distinct Characters]| |

‎src/162.c

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#include <stdio.h>
2+
#include <assert.h>
3+
4+
int findPeakElement(int* nums, int numsSize) {
5+
int left = 0, right = numsSize - 1, mid;
6+
while (left < right) {
7+
mid = left + (right - left) / 2;
8+
if ((mid == 0 && nums[mid] > nums[mid + 1])
9+
|| (mid == numsSize - 1 && nums[mid] > nums[mid - 1])
10+
|| (nums[mid] > nums[mid - 1] && nums[mid] > nums[mid + 1]))
11+
{
12+
return mid;
13+
}
14+
else if (nums[mid] < nums[mid + 1]) {
15+
left = mid + 1;
16+
}
17+
else if (nums[mid] < nums[mid - 1]) {
18+
right = mid - 1;
19+
}
20+
}
21+
22+
return left;
23+
}
24+
25+
int main() {
26+
int nums0[] = { 1, 2, 3, 1 };
27+
int nums0[] = { 1, 2 };
28+
assert(findPeakElement(sizeof(nums0) / sizeof(nums0[0])) == 2);
29+
assert(findPeakElement(sizeof(nums1) / sizeof(nums1[0])) == 1);
30+
return 0;
31+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /