桶排序
This commit is contained in:
@@ -1,9 +1,67 @@
|
||||
package com.dota.bucket;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import java.util.*;
|
||||
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) {
|
||||
Map<Long, Long> map = new HashMap<>();
|
||||
for (int i = 0; i < nums.length; i++) {
|
||||
|
Reference in New Issue
Block a user