Skip to content

Commit d9f9cda

Browse files
authored
feat: add swift implementation to lcci problem: No.16.06 (#2729)
1 parent 96154fb commit d9f9cda

File tree

3 files changed

+102
-0
lines changed

3 files changed

+102
-0
lines changed

Diff for: lcci/16.06.Smallest Difference/README.md

+35
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,41 @@ function smallestDifference(a: number[], b: number[]): number {
141141
}
142142
```
143143

144+
```swift
145+
class Solution {
146+
func smallestDifference(_ a: [Int], _ b: [Int]) -> Int {
147+
let sortedB = b.sorted()
148+
var ans = Int.max
149+
150+
for x in a {
151+
let j = search(sortedB, x)
152+
if j < sortedB.count {
153+
ans = min(ans, abs(sortedB[j] - x))
154+
}
155+
if j > 0 {
156+
ans = min(ans, abs(x - sortedB[j - 1]))
157+
}
158+
}
159+
160+
return ans
161+
}
162+
163+
private func search(_ nums: [Int], _ x: Int) -> Int {
164+
var l = 0
165+
var r = nums.count
166+
while l < r {
167+
let mid = (l + r) / 2
168+
if nums[mid] >= x {
169+
r = mid
170+
} else {
171+
l = mid + 1
172+
}
173+
}
174+
return l
175+
}
176+
}
177+
```
178+
144179
<!-- tabs:end -->
145180

146181
### 方法二:排序 + 双指针

Diff for: lcci/16.06.Smallest Difference/README_EN.md

+35
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,41 @@ function smallestDifference(a: number[], b: number[]): number {
147147
}
148148
```
149149

150+
```swift
151+
class Solution {
152+
func smallestDifference(_ a: [Int], _ b: [Int]) -> Int {
153+
let sortedB = b.sorted()
154+
var ans = Int.max
155+
156+
for x in a {
157+
let j = search(sortedB, x)
158+
if j < sortedB.count {
159+
ans = min(ans, abs(sortedB[j] - x))
160+
}
161+
if j > 0 {
162+
ans = min(ans, abs(x - sortedB[j - 1]))
163+
}
164+
}
165+
166+
return ans
167+
}
168+
169+
private func search(_ nums: [Int], _ x: Int) -> Int {
170+
var l = 0
171+
var r = nums.count
172+
while l < r {
173+
let mid = (l + r) / 2
174+
if nums[mid] >= x {
175+
r = mid
176+
} else {
177+
l = mid + 1
178+
}
179+
}
180+
return l
181+
}
182+
}
183+
```
184+
150185
<!-- tabs:end -->
151186

152187
### Solution 2: Sorting + Two Pointers

Diff for: lcci/16.06.Smallest Difference/Solution.swift

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
func smallestDifference(_ a: [Int], _ b: [Int]) -> Int {
3+
let sortedB = b.sorted()
4+
var ans = Int.max
5+
6+
for x in a {
7+
let j = search(sortedB, x)
8+
if j < sortedB.count {
9+
ans = min(ans, abs(sortedB[j] - x))
10+
}
11+
if j > 0 {
12+
ans = min(ans, abs(x - sortedB[j - 1]))
13+
}
14+
}
15+
16+
return ans
17+
}
18+
19+
private func search(_ nums: [Int], _ x: Int) -> Int {
20+
var l = 0
21+
var r = nums.count
22+
while l < r {
23+
let mid = (l + r) / 2
24+
if nums[mid] >= x {
25+
r = mid
26+
} else {
27+
l = mid + 1
28+
}
29+
}
30+
return l
31+
}
32+
}

0 commit comments

Comments
 (0)