add
This commit is contained in:
parent
5b53c56fd1
commit
a3b00e66e3
41
5.leetcode/src/com/fanxb/common/Q19.java
Normal file
41
5.leetcode/src/com/fanxb/common/Q19.java
Normal 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;
|
||||
|
||||
}
|
||||
}
|
32
5.leetcode/src/com/fanxb/common/Q347.java
Normal file
32
5.leetcode/src/com/fanxb/common/Q347.java
Normal 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)));
|
||||
}
|
||||
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user