Skip to content

Commit 589542d

Browse files
authored
feat: add swift implementation to lcci problem: No.17.14 (#2785)
1 parent 5c8134d commit 589542d

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed

lcci/17.14.Smallest K/README.md

+10
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,16 @@ func smallestK(arr []int, k int) []int {
7070
}
7171
```
7272

73+
```swift
74+
class Solution {
75+
func smallestK(_ arr: [Int], _ k: Int) -> [Int] {
76+
guard k > 0 else { return [] }
77+
let sortedArray = arr.sorted()
78+
return Array(sortedArray.prefix(k))
79+
}
80+
}
81+
```
82+
7383
<!-- tabs:end -->
7484

7585
### 方法二:优先队列(大根堆)

lcci/17.14.Smallest K/README_EN.md

+10
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,16 @@ func smallestK(arr []int, k int) []int {
6969
}
7070
```
7171

72+
```swift
73+
class Solution {
74+
func smallestK(_ arr: [Int], _ k: Int) -> [Int] {
75+
guard k > 0 else { return [] }
76+
let sortedArray = arr.sorted()
77+
return Array(sortedArray.prefix(k))
78+
}
79+
}
80+
```
81+
7282
<!-- tabs:end -->
7383

7484
### Solution 2

lcci/17.14.Smallest K/Solution.swift

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution {
2+
func smallestK(_ arr: [Int], _ k: Int) -> [Int] {
3+
guard k > 0 else { return [] }
4+
let sortedArray = arr.sorted()
5+
return Array(sortedArray.prefix(k))
6+
}
7+
}

0 commit comments

Comments
 (0)