-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution229.cs
71 lines (64 loc) · 1.47 KB
/
Solution229.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
namespace LeetCode.Solutions;
public class Solution229
{
/// <summary>
/// 229. Majority Element II - Medium
/// <a href="https://leetcode.com/problems/majority-element-ii">See the problem</a>
/// </summary>
public IList<int> MajorityElement(int[] nums)
{
var result = new List<int>();
var count1 = 0;
var count2 = 0;
var candidate1 = 0;
var candidate2 = 0;
foreach (var num in nums)
{
if (num == candidate1)
{
count1++;
}
else if (num == candidate2)
{
count2++;
}
else if (count1 == 0)
{
candidate1 = num;
count1 = 1;
}
else if (count2 == 0)
{
candidate2 = num;
count2 = 1;
}
else
{
count1--;
count2--;
}
}
count1 = 0;
count2 = 0;
foreach (var num in nums)
{
if (num == candidate1)
{
count1++;
}
else if (num == candidate2)
{
count2++;
}
}
if (count1 > nums.Length / 3)
{
result.Add(candidate1);
}
if (count2 > nums.Length / 3)
{
result.Add(candidate2);
}
return result;
}
}