牛客网: BM47
题目: 数组第K大的数
思路: 见最小的k个数,将num[right] > pivot的元素左调,最终返回num[k-1]
代码:
// gopackage main
// import "fmt"/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param a int整型一维数组 * @param n int整型 * @param K int整型 * @return int整型
*/
func findKth( input []int , n int , k int ) int {// write code hereif len(input) == 0 || len(input) < k || k == 0 {return -1}low := 0high := len(input) - 1for low < high {left := lowright := lowpivot := input[high]for right < high {if input[right] > pivot {input[left], input[right] = input[right], input[left]left++right++} else {right++}}input[left], input[high] = input[high], input[left]if left == k - 1 {break} else if left > k - 1 {high = left - 1} else {low = left + 1}}return input[k-1]
}