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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// @Title: 数组中的第K个最大元素 (Kth Largest Element in an Array)
// @Author: 15816537946@163.com
// @Date: 2020-06-25 07:15:36
// @Runtime: 12 ms
// @Memory: 3.5 MB
/*
 * @lc app=leetcode.cn id=215 lang=golang
 *
 * [215] 数组中的第K个最大元素
 *
 * https://leetcode-cn.com/problems/kth-largest-element-in-an-array/description/
 *
 * algorithms
 * Medium (58.03%)
 * Likes:    240
 * Dislikes: 0
 * Total Accepted:    40.5K
 * Total Submissions: 69.7K
 * Testcase Example:  '[3,2,1,5,6,4]\n2'
 *
 * 在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。
 *
 * 示例 1:
 *
 * 输入: [3,2,1,5,6,4] 和 k = 2
 * 输出: 5
 *
 *
 * 示例 2:
 *
 * 输入: [3,2,3,1,2,4,5,5,6] 和 k = 4
 * 输出: 4
 *
 * 说明:
 *
 * 你可以假设 k 总是有效的,且 1 ≤ k ≤ 数组的长度。
 *
 */

// quick sort

func findKthLargest(nums []int, k int) int {
	return doFindKthLargest(nums, k,0, len(nums)-1)
}

func doFindKthLargest(nums []int, k, start,end int) int {
	nLen := len(nums)
	targetPos := nLen-k

	for {
		povitIndex := partition(nums, start, end)
		if povitIndex == targetPos {
			return nums[povitIndex]
		} else if povitIndex > targetPos {
			end= povitIndex-1
		} else {
			start = povitIndex+1
		}
	}

}

func partition(nums []int, start, end int)  int {
	povit := nums[start]
	lo,hi := start+1, end

	for  lo<=hi{
		for lo <= hi && nums[lo]<=povit {
			lo++
		}
		for lo <= hi && nums[hi] > povit {
			hi--
		}
		if lo< hi {
			nums[lo],nums[hi] = nums[hi],nums[lo]
		}
	}
	nums[start], nums[hi] = nums[hi], nums[start]

	return hi
}