|
1 | 1 | package com.fishercoder.solutions; |
2 | 2 |
|
| 3 | +import java.util.Arrays; |
3 | 4 | import java.util.Collections; |
4 | 5 | import java.util.PriorityQueue; |
5 | 6 |
|
|
17 | 18 | */ |
18 | 19 | public class _215 { |
19 | 20 |
|
20 | | - public int findKthLargest(int[] nums, int k) { |
21 | | - PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); |
22 | | - for (int i : nums) { |
23 | | - maxHeap.offer(i); |
| 21 | + public static class Solution1 { |
| 22 | + public int findKthLargest(int[] nums, int k) { |
| 23 | + Arrays.sort(nums); |
| 24 | + return nums[nums.length - k]; |
24 | 25 | } |
25 | | - while (k-- > 1) { |
26 | | - maxHeap.poll(); |
| 26 | + } |
| 27 | + |
| 28 | + public static class Solution2 { |
| 29 | + public int findKthLargest(int[] nums, int k) { |
| 30 | + PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); |
| 31 | + for (int i : nums) { |
| 32 | + maxHeap.offer(i); |
| 33 | + } |
| 34 | + while (k-- > 1) { |
| 35 | + maxHeap.poll(); |
| 36 | + } |
| 37 | + return maxHeap.poll(); |
27 | 38 | } |
28 | | - return maxHeap.poll(); |
29 | 39 | } |
30 | 40 |
|
| 41 | + public static class Solution3 { |
| 42 | + /**Quick Select algorithm |
| 43 | + * Time: O(n) in average, O(n^2) in worst case |
| 44 | + * |
| 45 | + * Reference: https://discuss.leetcode.com/topic/14611/java-quick-select*/ |
| 46 | + public int findKthLargest(int[] nums, int k) { |
| 47 | + int start = 0; |
| 48 | + int end = nums.length - 1; |
| 49 | + int index = nums.length - k; |
| 50 | + while (start < end) { |
| 51 | + int pivot = partition(nums, start, end); |
| 52 | + if (pivot < index) start = pivot + 1; |
| 53 | + else if (pivot > index) end = pivot - 1; |
| 54 | + else return nums[pivot]; |
| 55 | + } |
| 56 | + return nums[start]; |
| 57 | + } |
| 58 | + |
| 59 | + int partition(int[] nums, int start, int end) { |
| 60 | + int pivot = start; |
| 61 | + while (start <= end) { |
| 62 | + while (start <= end && nums[start] <= nums[pivot]) { |
| 63 | + start++; |
| 64 | + } |
| 65 | + while (start <= end && nums[end] > nums[pivot]) { |
| 66 | + end--; |
| 67 | + } |
| 68 | + if (start > end) { |
| 69 | + break; |
| 70 | + } |
| 71 | + swap(nums, start, end); |
| 72 | + } |
| 73 | + swap(nums, end, pivot); |
| 74 | + return end; |
| 75 | + } |
| 76 | + |
| 77 | + void swap(int[] nums, int i, int j) { |
| 78 | + int temp = nums[i]; |
| 79 | + nums[i] = nums[j]; |
| 80 | + nums[j] = temp; |
| 81 | + } |
| 82 | + } |
31 | 83 | } |
0 commit comments