Skip to content

Commit 778d80d

Browse files
author
Yi Gu
committed
[Array] Add a solution to Majority Element II
1 parent 2fe9afd commit 778d80d

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Array/MajorityElementII.swift

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/majority-element-ii/
3+
* Primary idea: traverse the array and track the majority element accordingly, do not
4+
* forget to verify they are valid after first iteration
5+
*
6+
* Time Complexity: O(n), Space Complexity: O(1)
7+
*
8+
*/
9+
10+
class MajorityElementII {
11+
func majorityElement(_ nums: [Int]) -> [Int] {
12+
var num0: Int?
13+
var num1: Int?
14+
var count0 = 0
15+
var count1 = 0
16+
var res = [Int]()
17+
18+
for num in nums {
19+
if let num0 = num0, num0 == num {
20+
count0 += 1
21+
} else if let num1 = num1, num1 == num {
22+
count1 += 1
23+
} else if count0 == 0 {
24+
num0 = num
25+
count0 = 1
26+
} else if count1 == 0 {
27+
num1 = num
28+
count1 = 1
29+
} else {
30+
count0 -= 1
31+
count1 -= 1
32+
}
33+
}
34+
35+
count0 = 0
36+
count1 = 0
37+
38+
for num in nums {
39+
if num == num0 {
40+
count0 += 1
41+
}
42+
if num == num1 {
43+
count1 += 1
44+
}
45+
}
46+
47+
if count0 > nums.count / 3 {
48+
res.append(num0!)
49+
}
50+
if count1 > nums.count / 3 {
51+
res.append(num1!)
52+
}
53+
54+
return res
55+
}
56+
}

0 commit comments

Comments
 (0)