1 TopK问题
class Solution {
public int[][] kClosest(int[][] points, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((p1, p2)
-> p2[0]*p2[0]+p2[1]*p2[1] - p1[0]*p1[0] - p1[1]*p1[1]);
for(int[] point : points){
if(pq.size() < k){
pq.offer(point);
}else if(pq.comparator().compare(point, pq.peek())>0){
pq.poll();
pq.offer(point);
}
}
int[][] res = new int[pq.size()][2];
int idx = 0;
for(int[] point : pq){
res[idx++] = point;
}
return res;
}
}
class Solution {
public List<String> topKFrequent(String[] words, int k) {
int n = words.length;
Map<String, Integer> map = new HashMap<>();
for(String word : words){
if(map.get(word) != null){
int cnt = map.get(word);
cnt++;
map.put(word, cnt);
}else{
map.put(word, 1);
}
}
PriorityQueue<Object[]> pq = new PriorityQueue<>((a, b) -> {
int c1 = (Integer)a[1];
int c2 = (Integer)b[1];
if(c1 != c2) return c1-c2;
String s1 = (String)a[0];
String s2 = (String)b[0];
return s2.compareTo(s1);
});
for(String word : map.keySet()){
int cnt = map.get(word);
if(pq.size() < k){
pq.add(new Object[]{word, cnt});
}else{
Object[] peek = pq.peek();
if(cnt > (Integer)peek[1]){
pq.poll();
pq.offer(new Object[]{word, cnt});
}else if(cnt == (Integer)peek[1]){
String top = (String)peek[0];
if(word.compareTo(top) < 0){
pq.poll();
pq.add(new Object[]{word, cnt});
}
}
}
}
List<String> ans = new ArrayList<>();
while(!pq.isEmpty()) ans.add((String)pq.poll()[0]);
Collections.reverse(ans);
return ans;
}
}
2. 数据流中位数
class MedianFinder {
PriorityQueue<Integer> a,b;
public MedianFinder() {
a = new PriorityQueue<>();
b = new PriorityQueue<>((x, y) -> (y - x));
}
public void addNum(int num) {
if(a.size() != b.size()){
a.add(num);
b.add(a.poll());
}else{
b.add(num);
a.add(b.poll());
}
}
public double findMedian() {
return a.size()!=b.size() ? a.peek() : (a.peek()+b.peek())/2.0;
}
}
3. K路归并
class Solution {
class Status implements Comparable<Status>{
int val;
ListNode ptr;
Status(int val, ListNode ptr){
this.val = val;
this.ptr = ptr;
}
public int compareTo(Status s2){
return this.val - s2.val;
}
}
PriorityQueue<Status> queue = new PriorityQueue<Status>();
public ListNode mergeKLists(ListNode[] lists) {
for(ListNode node : lists){
if(node != null){
queue.offer(new Status(node.val, node));
}
}
ListNode head = new ListNode(0);
ListNode tail = head;
while(!queue.isEmpty()){
Status f = queue.poll();
tail.next = f.ptr;
tail = tail.next;
if(f.ptr.next != null){
queue.offer(new Status(f.ptr.next.val, f.ptr.next));
}
}
return head.next;
}
}