Refactored Solution In Swift

后端 未结 2 957
旧时难觅i
旧时难觅i 2021-01-24 13:29

I\'ve been studying for a coding exam by doing the HackerRank test cases, for the most part I\'ve been doing well, but I get hung up on some easy cases and you all help me when

2条回答
  •  半阙折子戏
    2021-01-24 13:30

    Thanks to @Alexander - I was able to solve this issue using NSCountedSet instead of my custom reduce method. It's much cleaner and more efficient. Here is the solution:

    import Foundation
    
    func main() -> String {
        let v = readLine()!.components(separatedBy: " ").map{Int($0)!}
        var a = [String](); var b = [String]()
        if v[0] < v[1] { return "No"}
        for i in 0 ..< 2 {
            if i == 0 {
                a = (readLine()!).components(separatedBy: " ")
            } else { b = (readLine()!).components(separatedBy: " ") }
        }
        let countA = NSCountedSet(array: a)
        let countB = NSCountedSet(array: b)
        let intersect = Set(a).intersection(Set(b))
        let check = intersect.map{ countB.count(for: $0) <= countA.count(for: $0) }
        return !check.contains(false) ? "Yes" : "No"
    }
    print(main())
    

    Many thanks!

提交回复
热议问题