package leetcode
import "sort"
func findKthLargest1(nums []int, k int) int {
sort.Ints(nums)
return nums[len(nums)-k]
}
func findKthLargest(nums []int, k int) int {
if len(nums) == 0 {
return 0
}
return selection(nums, 0, len(nums)-1, len(nums)-k)
}
func selection(arr []int, l, r, k int) int {
if l == r {
return arr[l]
}
p := partition164(arr, l, r)
if k == p {
return arr[p]
} else if k < p {
return selection(arr, l, p-1, k)
} else {
return selection(arr, p+1, r, k)
}
}
func partition164(a []int, lo, hi int) int {
pivot := a[hi]
i := lo - 1
for j := lo; j < hi; j++ {
if a[j] < pivot {
i++
a[j], a[i] = a[i], a[j]
}
}
a[i+1], a[hi] = a[hi], a[i+1]
return i + 1
}