forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[Array] Add solution to Majority Element
- Loading branch information
Yi Gu
committed
Sep 26, 2016
1 parent
7a2eb26
commit 446f638
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |