From 587bcfbfa3fff81905916aa4378283f53fdd5b60 Mon Sep 17 00:00:00 2001 From: Soap Date: Mon, 19 Aug 2019 19:52:39 -0700 Subject: [PATCH] [Math] Refactor solution to Majority Element --- Array/MajorityElement.swift | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/Array/MajorityElement.swift b/Array/MajorityElement.swift index 8185b372..39b42e9d 100644 --- a/Array/MajorityElement.swift +++ b/Array/MajorityElement.swift @@ -8,22 +8,16 @@ class MajorityElement { func majorityElement(_ nums: [Int]) -> Int { - var major = nums.first! - var sum = 0 + var count = 0, candidate = 0 for num in nums { - if num == major { - sum += 1 - } else { - sum -= 1 - } + if count == 0 { + candidate = num + } - if sum == 0 { - major = num - sum = 1 - } + count += (candidate == num) ? 1 : -1 } - return major + return candidate } -} \ No newline at end of file +}