LeetCode138:
题目描述:
代码:
class Solution {
public Node copyRandomList(Node head) {
if(head==null){return null;}
Map<Node,Node> map=new HashMap<>();
Node cur=head;
while(cur!=null){
Node node=new Node(cur.val);
map.put(cur,node);
cur=cur.next;
}
cur=head;
while(cur!=null){
map.get(cur).next=map.get(cur.next);
map.get(cur).random=map.get(cur.random);
cur=cur.next;
}
head=map.get(head);
return head;
}
}
LeetCode692:
题目描述:
代码:
class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> list=new ArrayList<>();
HashMap<String,Integer> map=new HashMap<>();
for(String s:words){
if(map.containsKey(s)){
Integer integer = map.get(s);
map.put(s,integer+1);
}else {
map.put(s,1);
}
}
//小堆
PriorityQueue<Map.Entry<String,Integer>> heap=new PriorityQueue<>(k, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
if(o1.getValue()-o2.getValue()==0){
return o2.getKey().compareTo(o1.getKey());
}
return o1.getValue()-o2.getValue();
}
});
Set<Map.Entry<String, Integer>> entries = map.entrySet();
for(Map.Entry<String,Integer> e:entries){
if(heap.size()<k){
heap.offer(e);
}else{
Map.Entry<String, Integer> peek = heap.peek();
if(peek.getValue()==e.getValue()){
if(peek.getKey().compareTo(e.getKey())>0){
heap.poll();
heap.offer(e);
}
}else {
if(peek.getValue()<e.getValue()){
heap.poll();
heap.offer(e);
}
}
}
}
System.out.println(heap);
for(int i=0;i<k;i++){
String key = heap.poll().getKey();
list.add(key);
}
Collections.reverse(list);
System.out.println(list);
return list;
}
}