LeetCode-138-692

本文解析了两道LeetCode题目:138. 复制随机链表,通过哈希映射实现链表节点的高效复制;692. 最高频单词,利用优先队列优化Top K频繁字符串查找。深入理解并掌握链表操作与数据结构优化技巧。
摘要由CSDN通过智能技术生成

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值