@@ -4,28 +4,50 @@ public class Main {
44
55 public static class Solution {
66
7- class MinStack {
8-
9- /** initialize your data structure here. */
10- public MinStack () {
11-
12- }
13-
14- public void push (int x ) {
7+ public int findKthLargest (int [] nums , int k ) {
8+ shuffle (nums );
9+ return findKthLargest (nums , 0 , nums .length - 1 , k );
10+ }
1511
12+ private void shuffle (int [] nums ) {
13+ Random rnd = new Random (System .currentTimeMillis ());
14+ for (int i = nums .length - 1 ; i > 1 ; i --) {
15+ int index = rnd .nextInt (i + 1 );
16+ swap (nums , index , i );
1617 }
18+ }
1719
18- public void pop () {
19-
20+ public int findKthLargest (int [] nums , int start , int end , int k ) {
21+ int index = partition (nums , start , end );
22+ int count = end - index + 1 ;
23+ if (count < k ) {
24+ return findKthLargest (nums , start , index - 1 , k - count );
25+ } else if (count > k ) {
26+ return findKthLargest (nums , index + 1 , end , k );
27+ } else {
28+ return nums [index ];
2029 }
30+ }
2131
22- public int top () {
23-
32+ private int partition (int [] nums , int start , int end ) {
33+ int left = start , right = end -1 , pivot = nums [end ];
34+ for (int i = start ; i < right ; ) {
35+ if (nums [i ] < pivot ) {
36+ swap (nums , left ++, i ++);
37+ } else if (nums [i ] > pivot ) {
38+ swap (nums , right --, i );
39+ } else {
40+ i ++;
41+ }
2442 }
43+ swap (nums , left , end );
44+ return left ;
45+ }
2546
26- public int getMin () {
27-
28- }
47+ private void swap (int [] nums , int i , int j ) {
48+ int t = nums [i ];
49+ nums [i ] = nums [j ];
50+ nums [j ] = t ;
2951 }
3052 }
3153
0 commit comments