diff --git a/lcci/17.10.Find Majority Element/README.md b/lcci/17.10.Find Majority Element/README.md index a7516dcf653e1..bda59b5cadc7d 100644 --- a/lcci/17.10.Find Majority Element/README.md +++ b/lcci/17.10.Find Majority Element/README.md @@ -184,6 +184,40 @@ public class Solution { } ``` +```swift +class Solution { + func majorityElement(_ nums: [Int]) -> Int { + var count = 0 + var candidate: Int? + + for num in nums { + if count == 0 { + candidate = num + count = 1 + } else if let candidate = candidate, candidate == num { + count += 1 + } else { + count -= 1 + } + } + + count = 0 + if let candidate = candidate { + for num in nums { + if num == candidate { + count += 1 + } + } + if count > nums.count / 2 { + return candidate + } + } + + return -1 + } +} +``` + diff --git a/lcci/17.10.Find Majority Element/README_EN.md b/lcci/17.10.Find Majority Element/README_EN.md index 0b853402f0b4f..9d3b44c3c67cf 100644 --- a/lcci/17.10.Find Majority Element/README_EN.md +++ b/lcci/17.10.Find Majority Element/README_EN.md @@ -177,6 +177,40 @@ public class Solution { } ``` +```swift +class Solution { + func majorityElement(_ nums: [Int]) -> Int { + var count = 0 + var candidate: Int? + + for num in nums { + if count == 0 { + candidate = num + count = 1 + } else if let candidate = candidate, candidate == num { + count += 1 + } else { + count -= 1 + } + } + + count = 0 + if let candidate = candidate { + for num in nums { + if num == candidate { + count += 1 + } + } + if count > nums.count / 2 { + return candidate + } + } + + return -1 + } +} +``` + diff --git a/lcci/17.10.Find Majority Element/Solution.swift b/lcci/17.10.Find Majority Element/Solution.swift new file mode 100644 index 0000000000000..39db645ff4290 --- /dev/null +++ b/lcci/17.10.Find Majority Element/Solution.swift @@ -0,0 +1,31 @@ +class Solution { + func majorityElement(_ nums: [Int]) -> Int { + var count = 0 + var candidate: Int? + + for num in nums { + if count == 0 { + candidate = num + count = 1 + } else if let candidate = candidate, candidate == num { + count += 1 + } else { + count -= 1 + } + } + + count = 0 + if let candidate = candidate { + for num in nums { + if num == candidate { + count += 1 + } + } + if count > nums.count / 2 { + return candidate + } + } + + return -1 + } +} \ No newline at end of file