diff --git a/lcci/17.14.Smallest K/README.md b/lcci/17.14.Smallest K/README.md index d24dd1b51eb2d..60d5092a5d5cb 100644 --- a/lcci/17.14.Smallest K/README.md +++ b/lcci/17.14.Smallest K/README.md @@ -70,6 +70,16 @@ func smallestK(arr []int, k int) []int { } ``` +```swift +class Solution { + func smallestK(_ arr: [Int], _ k: Int) -> [Int] { + guard k > 0 else { return [] } + let sortedArray = arr.sorted() + return Array(sortedArray.prefix(k)) + } +} +``` + ### 方法二:优先队列(大根堆) diff --git a/lcci/17.14.Smallest K/README_EN.md b/lcci/17.14.Smallest K/README_EN.md index 2aba87db0e53f..db9a66850ff8e 100644 --- a/lcci/17.14.Smallest K/README_EN.md +++ b/lcci/17.14.Smallest K/README_EN.md @@ -69,6 +69,16 @@ func smallestK(arr []int, k int) []int { } ``` +```swift +class Solution { + func smallestK(_ arr: [Int], _ k: Int) -> [Int] { + guard k > 0 else { return [] } + let sortedArray = arr.sorted() + return Array(sortedArray.prefix(k)) + } +} +``` + ### Solution 2 diff --git a/lcci/17.14.Smallest K/Solution.swift b/lcci/17.14.Smallest K/Solution.swift new file mode 100644 index 0000000000000..0206ce4847680 --- /dev/null +++ b/lcci/17.14.Smallest K/Solution.swift @@ -0,0 +1,7 @@ +class Solution { + func smallestK(_ arr: [Int], _ k: Int) -> [Int] { + guard k > 0 else { return [] } + let sortedArray = arr.sorted() + return Array(sortedArray.prefix(k)) + } +} \ No newline at end of file