Leetcode 215: Kth Largest Element in an Array
Posted Keep walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 215: Kth Largest Element in an Array相关的知识,希望对你有一定的参考价值。
Find 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.
For example,
Given [3,2,1,5,6,4]
and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array‘s length.
1 public class Solution { 2 public int FindKthLargest(int[] nums, int k) { 3 return QuickSelect(nums, 0, nums.Length - 1, nums.Length - k); 4 } 5 6 private int QuickSelect(int[] nums, int start, int end, int k) 7 { 8 if (start >= end) return nums[start]; 9 10 int i = start, j = start, pivot = nums[end]; 11 12 while (j < end) 13 { 14 if (nums[j] < pivot) 15 { 16 if (i != j) 17 { 18 var tmp = nums[j]; 19 nums[j] = nums[i]; 20 nums[i] = tmp; 21 } 22 23 i++; 24 } 25 26 j++; 27 } 28 29 if (i != end) 30 { 31 nums[end] = nums[i]; 32 nums[i] = pivot; 33 } 34 35 if (k == i - start) 36 { 37 return nums[i]; 38 } 39 else if (k > i - start) 40 { 41 return QuickSelect(nums, i + 1, end, k - i + start - 1); 42 } 43 else 44 { 45 return QuickSelect(nums, start, i - 1, k); 46 } 47 } 48 }
以上是关于Leetcode 215: Kth Largest Element in an Array的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ 215. Kth Largest Element in an Array 堆排序求解
LN : leetcode 215 Kth Largest Element in an Array
[LeetCode] 215. Kth Largest Element in an Array
leetcode 215. Kth Largest Element in an Array