Skip to content

Commit

Permalink
[Array] Add a solution to Majority Element II
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Nov 27, 2016
1 parent 2fe9afd commit 778d80d
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions Array/MajorityElementII.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Question Link: https://leetcode.com/problems/majority-element-ii/
* Primary idea: traverse the array and track the majority element accordingly, do not
* forget to verify they are valid after first iteration
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/

class MajorityElementII {
func majorityElement(_ nums: [Int]) -> [Int] {
var num0: Int?
var num1: Int?
var count0 = 0
var count1 = 0
var res = [Int]()

for num in nums {
if let num0 = num0, num0 == num {
count0 += 1
} else if let num1 = num1, num1 == num {
count1 += 1
} else if count0 == 0 {
num0 = num
count0 = 1
} else if count1 == 0 {
num1 = num
count1 = 1
} else {
count0 -= 1
count1 -= 1
}
}

count0 = 0
count1 = 0

for num in nums {
if num == num0 {
count0 += 1
}
if num == num1 {
count1 += 1
}
}

if count0 > nums.count / 3 {
res.append(num0!)
}
if count1 > nums.count / 3 {
res.append(num1!)
}

return res
}
}

0 comments on commit 778d80d

Please sign in to comment.