diff --git a/lcci/16.24.Pairs With Sum/README.md b/lcci/16.24.Pairs With Sum/README.md index e8e672431f3a4..1e7a86808334f 100644 --- a/lcci/16.24.Pairs With Sum/README.md +++ b/lcci/16.24.Pairs With Sum/README.md @@ -126,6 +126,29 @@ function pairSums(nums: number[], target: number): number[][] { } ``` +```swift +class Solution { + func pairSums(_ nums: [Int], _ target: Int) -> [[Int]] { + var countMap = [Int: Int]() + var ans = [[Int]]() + + for x in nums { + let y = target - x + if let yCount = countMap[y], yCount > 0 { + ans.append([x, y]) + countMap[y] = yCount - 1 + if countMap[y] == 0 { + countMap.removeValue(forKey: y) + } + } else { + countMap[x, default: 0] += 1 + } + } + return ans + } +} +``` + diff --git a/lcci/16.24.Pairs With Sum/README_EN.md b/lcci/16.24.Pairs With Sum/README_EN.md index d255145ccf12e..bbbd68f8dd12a 100644 --- a/lcci/16.24.Pairs With Sum/README_EN.md +++ b/lcci/16.24.Pairs With Sum/README_EN.md @@ -130,6 +130,29 @@ function pairSums(nums: number[], target: number): number[][] { } ``` +```swift +class Solution { + func pairSums(_ nums: [Int], _ target: Int) -> [[Int]] { + var countMap = [Int: Int]() + var ans = [[Int]]() + + for x in nums { + let y = target - x + if let yCount = countMap[y], yCount > 0 { + ans.append([x, y]) + countMap[y] = yCount - 1 + if countMap[y] == 0 { + countMap.removeValue(forKey: y) + } + } else { + countMap[x, default: 0] += 1 + } + } + return ans + } +} +``` + diff --git a/lcci/16.24.Pairs With Sum/Solution.swift b/lcci/16.24.Pairs With Sum/Solution.swift new file mode 100644 index 0000000000000..cdf8f2b922bd8 --- /dev/null +++ b/lcci/16.24.Pairs With Sum/Solution.swift @@ -0,0 +1,20 @@ +class Solution { + func pairSums(_ nums: [Int], _ target: Int) -> [[Int]] { + var countMap = [Int: Int]() + var ans = [[Int]]() + + for x in nums { + let y = target - x + if let yCount = countMap[y], yCount > 0 { + ans.append([x, y]) + countMap[y] = yCount - 1 + if countMap[y] == 0 { + countMap.removeValue(forKey: y) + } + } else { + countMap[x, default: 0] += 1 + } + } + return ans + } +} \ No newline at end of file