forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthLargestElementInArray.swift
More file actions
29 lines (25 loc) · 940 Bytes
/
KthLargestElementInArray.swift
File metadata and controls
29 lines (25 loc) · 940 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Question Link: https://leetcode.com/problems/kth-largest-element-in-an-array/
* Primary idea: Quick sort
* Time Complexity: O(nlogn), Space Complexity: O(n)
*/
class KthLargestElementInArray {
func findKthLargest(_ nums: [Int], _ k: Int) -> Int {
guard let pivot = nums.first else {
fatalError("Invalid Input")
}
let leftPart = nums.filter { $0 > pivot }
let middlePart = nums.filter { $0 == pivot}
let rightPart = nums.filter { $0 < pivot }
if nums.count == middlePart.count {
return pivot
}
if leftPart.count > k - 1 {
return findKthLargest(leftPart, k)
} else if k - leftPart.count <= middlePart.count {
return findKthLargest(middlePart, k - leftPart.count)
} else {
return findKthLargest(rightPart, k - leftPart.count - middlePart.count)
}
}
}