/
914_X_of_a_Kind_in_a_Deck_of_Cards.swift
70 lines (61 loc) · 1.56 KB
/
914_X_of_a_Kind_in_a_Deck_of_Cards.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import Foundation
// Brute force.
class Solution {
func hasGroupsSizeX(_ deck: [Int]) -> Bool {
guard deck.count > 1 else {
return false
}
var cardCount = [Int: Int]()
for card in deck {
cardCount[card, default: 0] += 1
}
var N = deck.count
for X in 2...N {
var found = true
for (key, value) in cardCount {
if value % X != 0 {
found = false
break
}
}
if found {
return found
}
}
return false
}
}
// GCD
class Solution {
func hasGroupsSizeX(_ deck: [Int]) -> Bool {
guard deck.count > 1 else {
return false
}
var cardCount = [Int: Int]()
for card in deck {
cardCount[card, default: 0] += 1
}
let gcdLocal = gcd(of: cardCount.values.sorted())
return gcdLocal > 1 ? true : false
}
/// Euclid's algorithm to find GCD
/// - Parameters:
/// - array: array to find cd for
/// - Returns: gcd
func gcd(of array: [Int]) -> Int {
return array.reduce(0, gcd(_:_:))
}
/// Euclid's algorithm to find GCD
/// - Parameters:
/// - a: larger integer
/// - b: smaller integer
/// - Returns: gcd
func gcd(_ a: Int, _ b: Int) -> Int {
let r = a % b
if r != 0 {
return gcd(b, r)
} else {
return b
}
}
}