This commit is contained in:
fanxb 2022-01-27 16:22:49 +08:00
parent 5b53c56fd1
commit a3b00e66e3
2 changed files with 73 additions and 0 deletions

View File

@ -0,0 +1,41 @@
package com.fanxb.common;
public class Q19 {
public static class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p = head, q = head;
//先将p,q的距离差拉到n,这样当q在结尾时刚好p在倒数第n+1个位置上删除下一个位置即可
while ((n--) > 0) {
q = q.next;
}
//考虑特殊情况当n等于链表长度时需要删除第一个元素
if (q == null) {
return p.next;
}
//让q走到结尾
while (q.next != null) {
q = q.next;
p = p.next;
}
//删除p的下一个节点
p.next = p.next.next;
return head;
}
}

View File

@ -0,0 +1,32 @@
package com.fanxb.common;
import java.util.*;
public class Q347 {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> countMap = new HashMap<>();
for (int num : nums) {
int count = countMap.getOrDefault(num, 0) + 1;
countMap.put(num, count);
}
PriorityQueue<Integer> res = new PriorityQueue<>(Comparator.comparingInt(countMap::get));
for (int num : countMap.keySet()) {
if (res.size() < k) {
res.add(num);
} else if (countMap.get(res.peek()) < countMap.get(num)) {
res.poll();
res.add(num);
}
}
int[] realRes = new int[k];
for (int i = 0; i < k; i++) {
realRes[i] = res.poll();
}
return realRes;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new Q347().topKFrequent(new int[]{1}, 1)));
}
}