桶排序

This commit is contained in:
kkunkka
2025-03-05 16:15:51 +08:00
parent da762c35ed
commit 60dfa47549

View File

@@ -1,9 +1,67 @@
package com.dota.bucket; package com.dota.bucket;
import java.util.HashMap; import java.util.*;
import java.util.Map;
class Solution { class Solution {
public int[] topKFrequent(int[] nums, int k) {
var book = new ArrayList<ArrayList<Integer>>(nums.length+1);
var map = new HashMap<Integer, Integer>();
int i = 0;
for (int num : nums) {
map.put(num, map.getOrDefault(num, 0) + 1);
book.add(i++, new ArrayList<>());
}
book.add(new ArrayList<>());
var res = new int[k];
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
book.get(entry.getValue()).add(entry.getKey());
}
i = nums.length;
var index = 0;
for (;i>=0&&index<k;i--) {
if (!book.get(i).isEmpty()) {
for(var j = 0;j<book.get(i).size();j++) {
res[index++] = book.get(i).get(j);
}
}
}
return res;
}
}
class Solution3 {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> map = new HashMap<>();
var book = new int[words.length];
var res = new ArrayList<String>();
for (int i = 0; i < words.length; i++) {
if (map.containsKey(words[i])) {
book[map.get(words[i])]++;
} else {
map.put(words[i], i);
book[i] = 1;
}
}
for (int i = 0; i < k; i++) {
var max = 0;
for (int j = 0; j < book.length; j++) {
if (book[j] > book[max]) {
max = j;
}else if (book[j] == book[max]) {
max = words[j].compareTo(words[max]) > 0 ? max : j;
}
}
book[max] = 0;
res.add(words[max]);
}
return res;
}
}
class Solution2 {
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) { public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
Map<Long, Long> map = new HashMap<>(); Map<Long, Long> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) { for (int i = 0; i < nums.length; i++) {