当前位置:   article > 正文

leetcode刷题笔记(Golang)--215. Kth Largest Element in an Array_golang215

golang215

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
}
  • 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
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/206274
推荐阅读
相关标签
  

闽ICP备14008679号