2024/9/19 Hot100 Heap 昨日堆

This commit is contained in:
linlihong 2024-09-19 17:58:00 +08:00
parent 8e4d8d1ddd
commit dd6ea6ae2f
1 changed files with 68 additions and 0 deletions

View File

@ -0,0 +1,68 @@
package com.cool.hot100.heap;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/09/19/11:11
* DayNumber 1
* Hard 2
* Level ?
*/
public class Num215 {
/**
* 桶排序
*
* @param nums
* @param k
* @return
*/
public int findKthLargest(int[] nums, int k) {
int[] buckets = new int[20001];
for (int i = 0; i < nums.length; i++) {
buckets[nums[i] + 10000]++;
}
for (int i = 20000; i >= 0; i--) {
k = k - buckets[i];
if (k <= 0) {
return i - 10000;
}
}
return 0;
}
/**
* 快速排序思路参考双路快速排序
*
* @param nums
* @param k
* @return
*/
public int findKthLargest1(int[] nums, int k) {
return quickSearch(nums, 0, nums.length - 1, nums.length - k);
}
private int quickSearch(int[] nums, int left, int right, int k) {
if (left == right)
return nums[k];
int num = nums[left], i = left - 1, j = right + 1;
while (i < j) {
do
i++;
while (nums[i] < num);
do
j--;
while (nums[j] > num);
if (i < j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
if (k <= j) {
return quickSearch(nums, left, j, k);
} else {
return quickSearch(nums, j + 1, right, k);
}
}
}