-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmajority-element.swift
More file actions
24 lines (20 loc) · 3.12 KB
/
majority-element.swift
File metadata and controls
24 lines (20 loc) · 3.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func majorityElement(input: [Int]) -> Int? {
var counts = [Int:Int]()
for element in input {
if let value = counts[element] {
counts[element] = value + 1
} else {
counts[element] = 1
}
}
var result: Int?
for (element, count) in counts {
if count > input.count / 2 {
result = element
}
}
return result
}
// NOTE(hofer, 2014-10-26): Currently I'm not aware of a way to read arbitrary files (ie not inside of an ios app) in Swift, so this is a copy-and-paste of contents of small-input.txt.
var input = [1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,2,3,1,1,1,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