Skip to content

Commit 2fedf84

Browse files
authored
feat: add swift implementation to lcci problem: No.16.24 (#2766)
1 parent c4038aa commit 2fedf84

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

lcci/16.24.Pairs With Sum/README.md

+23
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,29 @@ function pairSums(nums: number[], target: number): number[][] {
126126
}
127127
```
128128

129+
```swift
130+
class Solution {
131+
func pairSums(_ nums: [Int], _ target: Int) -> [[Int]] {
132+
var countMap = [Int: Int]()
133+
var ans = [[Int]]()
134+
135+
for x in nums {
136+
let y = target - x
137+
if let yCount = countMap[y], yCount > 0 {
138+
ans.append([x, y])
139+
countMap[y] = yCount - 1
140+
if countMap[y] == 0 {
141+
countMap.removeValue(forKey: y)
142+
}
143+
} else {
144+
countMap[x, default: 0] += 1
145+
}
146+
}
147+
return ans
148+
}
149+
}
150+
```
151+
129152
<!-- tabs:end -->
130153

131154
<!-- end -->

lcci/16.24.Pairs With Sum/README_EN.md

+23
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,29 @@ function pairSums(nums: number[], target: number): number[][] {
130130
}
131131
```
132132

133+
```swift
134+
class Solution {
135+
func pairSums(_ nums: [Int], _ target: Int) -> [[Int]] {
136+
var countMap = [Int: Int]()
137+
var ans = [[Int]]()
138+
139+
for x in nums {
140+
let y = target - x
141+
if let yCount = countMap[y], yCount > 0 {
142+
ans.append([x, y])
143+
countMap[y] = yCount - 1
144+
if countMap[y] == 0 {
145+
countMap.removeValue(forKey: y)
146+
}
147+
} else {
148+
countMap[x, default: 0] += 1
149+
}
150+
}
151+
return ans
152+
}
153+
}
154+
```
155+
133156
<!-- tabs:end -->
134157

135158
<!-- end -->
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
func pairSums(_ nums: [Int], _ target: Int) -> [[Int]] {
3+
var countMap = [Int: Int]()
4+
var ans = [[Int]]()
5+
6+
for x in nums {
7+
let y = target - x
8+
if let yCount = countMap[y], yCount > 0 {
9+
ans.append([x, y])
10+
countMap[y] = yCount - 1
11+
if countMap[y] == 0 {
12+
countMap.removeValue(forKey: y)
13+
}
14+
} else {
15+
countMap[x, default: 0] += 1
16+
}
17+
}
18+
return ans
19+
}
20+
}

0 commit comments

Comments
 (0)