Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b506739

Browse files
feat: add swift implementation to lcof2 problem: No.076 (doocs#3410)
1 parent 8e3db9e commit b506739

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

‎lcof2/剑指 Offer II 076. 数组中的第 k 大的数字/README.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,41 @@ func quickSort(nums []int, left, right, k int) int {
180180
}
181181
```
182182

183+
#### Swift
184+
185+
```swift
186+
class Solution {
187+
func findKthLargest(_ nums: [Int], _ k: Int) -> Int {
188+
var nums = nums
189+
let n = nums.count
190+
return quickSelect(&nums, 0, n - 1, n - k)
191+
}
192+
193+
private func quickSelect(_ nums: inout [Int], _ left: Int, _ right: Int, _ k: Int) -> Int {
194+
if left == right {
195+
return nums[left]
196+
}
197+
198+
var i = left - 1
199+
var j = right + 1
200+
let pivot = nums[(left + right) / 2]
201+
202+
while i < j {
203+
repeat { i += 1 } while nums[i] < pivot
204+
repeat { j -= 1 } while nums[j] > pivot
205+
if i < j {
206+
nums.swapAt(i, j)
207+
}
208+
}
209+
210+
if j < k {
211+
return quickSelect(&nums, j + 1, right, k)
212+
}
213+
return quickSelect(&nums, left, j, k)
214+
}
215+
}
216+
```
217+
183218
<!-- tabs:end -->
184219

185220
<!-- solution:end -->
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
func findKthLargest(_ nums: [Int], _ k: Int) -> Int {
3+
var nums = nums
4+
let n = nums.count
5+
return quickSelect(&nums, 0, n - 1, n - k)
6+
}
7+
8+
private func quickSelect(_ nums: inout [Int], _ left: Int, _ right: Int, _ k: Int) -> Int {
9+
if left == right {
10+
return nums[left]
11+
}
12+
13+
var i = left - 1
14+
var j = right + 1
15+
let pivot = nums[(left + right) / 2]
16+
17+
while i < j {
18+
repeat { i += 1 } while nums[i] < pivot
19+
repeat { j -= 1 } while nums[j] > pivot
20+
if i < j {
21+
nums.swapAt(i, j)
22+
}
23+
}
24+
25+
if j < k {
26+
return quickSelect(&nums, j + 1, right, k)
27+
}
28+
return quickSelect(&nums, left, j, k)
29+
}
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /