Skip to content

Commit a614b2f

Browse files
authored
Merge pull request neetcode-gh#1336 from julienChemillier/patch-23
Add 169 in c language
2 parents 6f3d7d4 + 9e640cc commit a614b2f

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

c/169-Majority-Element.c

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/*
2+
Given an array nums of size n, return the majority element.
3+
4+
Space: O(1)
5+
Time: O(n)
6+
*/
7+
8+
int majorityElement(int* nums, int numsSize){
9+
int candidate=nums[0];
10+
int count=1;
11+
for (int i=1; i<numsSize; i++) {
12+
if (candidate==nums[i]) {
13+
count++;
14+
} else {
15+
count--;
16+
if (count==0) {
17+
count=1;
18+
candidate=nums[i];
19+
}
20+
}
21+
}
22+
return candidate;
23+
}

0 commit comments

Comments
 (0)