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
| class Solution { func findRestaurant(_ list1: [String], _ list2: [String]) -> [String] { var dict2 = [String: Int](), least = Int.max, arr = [String]() for i in 0..<list2.count { dict2[ list2[i] ] = i } for i in 0..<list1.count { if let j = dict2[ list1[i] ] { let n = i+j if n < least { arr = [list1[i]] least = n } else if n == least { arr.append(list1[i]) } } } return arr }
func findRestaurant(_ list1: [String], _ list2: [String]) -> [String] { let dict1 = list1.enumerated().reduce(into: [String: Int]()) { $0[$1.1] = $1.0 } let dict2 = list2.enumerated().reduce(into: [String: Int]()) { $0[$1.1] = $1.0 } let dict = Set(dict1.keys).intersection(dict2.keys).reduce(into: [String: Int]()) { $0[$1] = dict1[$1]! + dict2[$1]! }
return dict.filter { $0.value == dict.map({ $0.value }).min() }.map { $0.key } } }
|