-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMajorityElement.cs
37 lines (34 loc) · 949 Bytes
/
MajorityElement.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
public class Solution {
public int MajorityElement(int[] nums)
{
if (nums == null || nums.Length == 0)
return -1;
var length = nums.Length;
var majority = nums[0];
var count = 1;
var hasMajority = true;
for (int i = 1; i < length; i++)
{
var current = nums[i];
if (hasMajority)
{
if (current == majority)
{
count++;
}
else
{
count--;
}
hasMajority = count > 0;
}
else
{
count = 1;
hasMajority = true;
majority = nums[i];
}
}
return majority;
}
}