classSolution{ privatevar setI =Set<Int>() funcisHappy(_n: Int) -> Bool { if n ==1 { returntrue } var i = n, r =0 while i >0 { let t = i%10 r += t*t i /=10 }
classSolution{ // 452 ms funcfindRestaurant(_list1: [String], _list2: [String]) -> [String] { var dict2 = [String: Int](), least =Int.max, arr = [String]() for i in0..<list2.count { dict2[ list2[i] ] = i } for i in0..<list1.count { iflet j = dict2[ list1[i] ] { let n = i+j if n < least { arr = [list1[i]] least = n } elseif n == least { arr.append(list1[i]) } } } return arr }
classSolution{ funcintersect(_nums1: [Int], _nums2: [Int]) -> [Int] { var dict = [Int: Int](), ans = [Int]() for n in nums1 { dict[n, default: 0] +=1 } for n in nums2 { iflet v = dict[n], v >0 { ans.append(n) dict[n] = v -1 } } return ans } }
classSolution{ funcgroupStrings(_strings: [String]) -> [[String]] { var dict = [[Int]: [String]]() for s in strings { let arrS =Array(s) var arr = [Int]() for i in (1..<arrS.count) { arr.append((Int(arrS[i].asciiValue!)-Int(arrS[i-1].asciiValue!)+26)%26) } dict[arr, default: []] += [s] } return dict.map { $0.value } } }
classSolution{ funcisValidSudoku(_board: [[Character]]) -> Bool { var sets =Array(repeating: Set<Character>(), count: 9) for i in0..<9 { for j in0..<9 { let c = board[i][j] if c =="." { continue } if sets[i].contains(c) { returnfalse } else { sets[i].insert(c) } } }
sets =Array(repeating: Set<Character>(), count: 9) for j in0..<9 { for i in0..<9 { let c = board[i][j] if c =="." { continue } if sets[j].contains(c) { returnfalse } else { sets[j].insert(c) } } }
for i in0..<3 { for j in0..<3 { var setC =Set<Character>() for k in0..<3 { for l in0..<3 { let c = board[i*3+k][j*3+l] if c =="." { continue } if setC.contains(c) { returnfalse } else { setC.insert(c) } } }
classSolution{ funcfourSumCount(_A: [Int], _B: [Int], _C: [Int], _D: [Int]) -> Int { var num =0, ab = [Int: Int]() for i inA { for j inB { ab[i+j, default: 0] +=1 } } for i inC { for j inD { iflet v = ab[-i-j] { num += v } } } return num } }