Skip to content

Commit

Permalink
[Array] Add solution to Majority Element
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Sep 26, 2016
1 parent 7a2eb26 commit 446f638
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions Array/MajorityElement.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Question Link: https://leetcode.com/problems/majority-element/
* Primary idea: traverse the array and track the majority element accordingly
*
* Time Complexity: O(n), Space Complexity: O(1)
*
*/

class MajorityElement {
func majorityElement(_ nums: [Int]) -> Int {
var major = nums.first!
var sum = 0

for num in nums {
if num == major {
sum += 1
} else {
sum -= 1
}

if sum == 0 {
major = num
sum = 1
}
}

return major
}
}

0 comments on commit 446f638

Please sign in to comment.