Created
March 15, 2021 10:34
-
-
Save dmsl1805/dc14ae03ac09291eb2f9de07977b5d63 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
func countPairs(numbers: [Int], k: Int) -> Int { | |
struct Pair: Equatable, Hashable { | |
let lhs: Int | |
let rhs: Int | |
func isValid(k: Int) -> Bool { | |
return lhs + k == rhs | |
} | |
static func ==(lhs: Pair, rhs: Pair) -> Bool { | |
return rhs.contains(element: lhs.lhs) || rhs.contains(element: lhs.rhs) | |
} | |
private func contains(element: Int) -> Bool { | |
return lhs == element || rhs == element | |
} | |
} | |
struct ValidPairsContainer { | |
private var pairs: Set<Pair> = [] | |
var count: Int { | |
return pairs.count | |
} | |
mutating func appendIfValid(lhs: Int, rhs: Int, k: Int) { | |
let pair = Pair(lhs: lhs, rhs: rhs) | |
guard pair.isValid(k: k) else { return } | |
pairs.insert(pair) | |
} | |
} | |
var container = ValidPairsContainer() | |
let numbersSet = Set(numbers) | |
numbersSet.forEach { lhsNumber in | |
let rhsNumber = lhsNumber + k | |
guard numbersSet.contains(rhsNumber) else { return } | |
container.appendIfValid(lhs: lhsNumber, rhs: rhsNumber, k: k) | |
} | |
return container.count | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment