-
Notifications
You must be signed in to change notification settings - Fork 112
/
0215-KthLargestElementInAnArray.cs
64 lines (56 loc) · 1.67 KB
/
0215-KthLargestElementInAnArray.cs
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
//-----------------------------------------------------------------------------
// Runtime: 100ms
// Memory Usage: 25.3 MB
// Link: https://leetcode.com/submissions/detail/380544121/
//-----------------------------------------------------------------------------
using System;
namespace LeetCode
{
public class _0215_KthLargestElementInAnArray
{
public int FindKthLargest(int[] nums, int k)
{
Suffle(nums);
Quick3WaySort(nums, 0, nums.Length - 1, k);
return nums[k - 1];
}
private void Suffle(int[] nums)
{
var random = new Random();
int N = nums.Length;
int r, temp;
for (int i = 0; i < N; i++)
{
r = random.Next(i + 1);
temp = nums[r];
nums[r] = nums[i];
nums[i] = temp;
}
}
private void Swap(int[] nums, int i, int j)
{
var temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private void Quick3WaySort(int[] nums, int lo, int hi, int k)
{
if (lo >= hi) return;
if (lo >= k) return;
if (hi < k - 1) return;
int lt = hi, gt = lo, i = lo;
int pivot = nums[i];
while (i <= lt)
{
if (nums[i] > pivot)
Swap(nums, gt++, i);
else if (nums[i] < pivot)
Swap(nums, lt--, i);
else
i++;
}
Quick3WaySort(nums, lo, gt - 1, k);
Quick3WaySort(nums, lt + 1, hi, k);
}
}
}