Skip to content
/ leetcode Public
  • Sponsor doocs/leetcode

  • Notifications You must be signed in to change notification settings
  • Fork 9.1k
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit eeebf6c

Browse files
authoredMay 8, 2024
feat: add swift implementation to lcci problem: No.16.21 (#2764)
1 parent 47355fb commit eeebf6c

File tree

3 files changed

+90
-0
lines changed

3 files changed

+90
-0
lines changed
 

‎lcci/16.21.Sum Swap/README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,37 @@ function findSwapValues(array1: number[], array2: number[]): number[] {
148148
}
149149
```
150150

151+
```swift
152+
class Solution {
153+
func findSwapValues(_ array1: [Int], _ array2: [Int]) -> [Int] {
154+
var s1 = 0, s2 = 0
155+
var set = Set<Int>()
156+
157+
for x in array1 {
158+
s1 += x
159+
}
160+
for x in array2 {
161+
s2 += x
162+
set.insert(x)
163+
}
164+
165+
let diff = s1 - s2
166+
if diff % 2 != 0 {
167+
return []
168+
}
169+
let target = diff / 2
170+
171+
for a in array1 {
172+
let b = a - target
173+
if set.contains(b) {
174+
return [a, b]
175+
}
176+
}
177+
return []
178+
}
179+
}
180+
```
181+
151182
<!-- tabs:end -->
152183

153184
<!-- end -->

‎lcci/16.21.Sum Swap/README_EN.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,37 @@ function findSwapValues(array1: number[], array2: number[]): number[] {
154154
}
155155
```
156156

157+
```swift
158+
class Solution {
159+
func findSwapValues(_ array1: [Int], _ array2: [Int]) -> [Int] {
160+
var s1 = 0, s2 = 0
161+
var set = Set<Int>()
162+
163+
for x in array1 {
164+
s1 += x
165+
}
166+
for x in array2 {
167+
s2 += x
168+
set.insert(x)
169+
}
170+
171+
let diff = s1 - s2
172+
if diff % 2 != 0 {
173+
return []
174+
}
175+
let target = diff / 2
176+
177+
for a in array1 {
178+
let b = a - target
179+
if set.contains(b) {
180+
return [a, b]
181+
}
182+
}
183+
return []
184+
}
185+
}
186+
```
187+
157188
<!-- tabs:end -->
158189

159190
<!-- end -->

‎lcci/16.21.Sum Swap/Solution.swift

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
func findSwapValues(_ array1: [Int], _ array2: [Int]) -> [Int] {
3+
var s1 = 0, s2 = 0
4+
var set = Set<Int>()
5+
6+
for x in array1 {
7+
s1 += x
8+
}
9+
for x in array2 {
10+
s2 += x
11+
set.insert(x)
12+
}
13+
14+
let diff = s1 - s2
15+
if diff % 2 != 0 {
16+
return []
17+
}
18+
let target = diff / 2
19+
20+
for a in array1 {
21+
let b = a - target
22+
if set.contains(b) {
23+
return [a, b]
24+
}
25+
}
26+
return []
27+
}
28+
}

0 commit comments

Comments
 (0)
Please sign in to comment.