赞
踩
215. Kth Largest Element in an Array
nd the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
Example 1:
Input: [3,2,1,5,6,4] and k = 2
Output: 5
Example 2:
Input: [3,2,3,1,2,4,5,5,6] and k = 4
Output: 4
func findKthLargest(nums []int, k int) int { l:=0 r:= len(nums)-1 for { pos := partition(&nums,l,r) if pos == k-1 { return nums[pos] } else if pos > k-1 { r = pos-1 } else { l = pos + 1 } } } func partition(nums *[]int,l int, r int) int { pivot := (*nums)[l] pIndex := l l++ for l <= r { if (*nums)[l] < pivot && (*nums)[r] > pivot { (*nums)[l], (*nums)[r] = (*nums)[r],(*nums)[l] } if (*nums)[l] >= pivot { l++ } if (*nums)[r] <= pivot { r-- } } (*nums)[pIndex], (*nums)[r] = (*nums)[r],(*nums)[pIndex] return r }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。