diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/README.md" "b/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/README.md" index 3832f7087e47a..7b9be98b5e3da 100644 --- "a/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/README.md" +++ "b/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/README.md" @@ -180,6 +180,41 @@ func quickSort(nums []int, left, right, k int) int { } ``` +#### Swift + +```swift +class Solution { + func findKthLargest(_ nums: [Int], _ k: Int) -> Int { + var nums = nums + let n = nums.count + return quickSelect(&nums, 0, n - 1, n - k) + } + + private func quickSelect(_ nums: inout [Int], _ left: Int, _ right: Int, _ k: Int) -> Int { + if left == right { + return nums[left] + } + + var i = left - 1 + var j = right + 1 + let pivot = nums[(left + right) / 2] + + while i < j { + repeat { i += 1 } while nums[i] < pivot + repeat { j -= 1 } while nums[j] > pivot + if i < j { + nums.swapAt(i, j) + } + } + + if j < k { + return quickSelect(&nums, j + 1, right, k) + } + return quickSelect(&nums, left, j, k) + } +} +``` + diff --git "a/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/Solution.swift" "b/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/Solution.swift" new file mode 100644 index 0000000000000..357311f343c0e --- /dev/null +++ "b/lcof2/\345\211\221\346\214\207 Offer II 076. \346\225\260\347\273\204\344\270\255\347\232\204\347\254\254 k \345\244\247\347\232\204\346\225\260\345\255\227/Solution.swift" @@ -0,0 +1,30 @@ +class Solution { + func findKthLargest(_ nums: [Int], _ k: Int) -> Int { + var nums = nums + let n = nums.count + return quickSelect(&nums, 0, n - 1, n - k) + } + + private func quickSelect(_ nums: inout [Int], _ left: Int, _ right: Int, _ k: Int) -> Int { + if left == right { + return nums[left] + } + + var i = left - 1 + var j = right + 1 + let pivot = nums[(left + right) / 2] + + while i < j { + repeat { i += 1 } while nums[i] < pivot + repeat { j -= 1 } while nums[j] > pivot + if i < j { + nums.swapAt(i, j) + } + } + + if j < k { + return quickSelect(&nums, j + 1, right, k) + } + return quickSelect(&nums, left, j, k) + } +} \ No newline at end of file