美文网首页
2022-03-10 优先队列 找第k个数字,合并k个升序链表

2022-03-10 优先队列 找第k个数字,合并k个升序链表

作者: 16孙一凡通工 | 来源:发表于2022-03-10 10:13 被阅读0次

    多叉树遍历。
    送分题:
    java版本:

    
    class Solution {
        List<Integer> res=new ArrayList<>();
        public List<Integer> preorder(Node root) {
            if(root==null){
                return res;
            }
            res.add(root.val);
            for(Node child:root.children){
                preorder(child);
            }
            return res;
        
        }
    }
    

    优先队列的题目总是不太敏感,还要多练

    23. 合并K个升序链表

    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
    
        //     PriorityQueue<Integer> queue=new PriorityQueue<>(new Comparator<int[]>(){
        //    public int compare(int m1,int m2){
        //        return m1-m2;
    
        //    }
        //     });
             PriorityQueue<Integer> queue = new PriorityQueue<>(new Comparator<Integer>() {
                public int compare(Integer m, Integer n) {
                    return m - n;
                }
            });
                
            for(ListNode list:lists){
              while(list!=null){
                  queue.add(list.val);
                  list=list.next;
              }
        
            }
    
            
            ListNode res=new ListNode(0);
            ListNode node=res;
             while(queue.size()>0){
              
              ListNode temp=new ListNode(queue.peek());
              queue.poll();
              node.next=temp;
              node=node.next;
    
            }
            return res.next;
           
        }
    }
    

    剑指 Offer II 060. 出现频率最高的 k 个数字

    class Solution {
        public int[] topKFrequent(int[] nums, int k) {
            // 找个东西统计出现次数。
            // 然后 把key  value放到优先队列当中
            HashMap<Integer,Integer> hashmap=new HashMap<>();
            PriorityQueue<int[]> queue=new PriorityQueue<>(new  Comparator(){
                public int compare(int[] m1,int[] m2){
                    return m2[1]-m1[1];
    
                }
            });
    
            for(int key:nums){
                hashmap[key]++;
            }
            for(Integer key:hashmap.keySet()){
                queue.add(new int[]{key, hashmap[key]});
            }
            while(queue.size()>k){
                queue.poll();
           
            }
            int[] res=new int[k];
            for(int i=k-1;i>=0;i--){
                
                res[i]=queue.peek();
                queue.poll();
            }
            return res;
            
        }
    }
    

    相关文章

      网友评论

          本文标题:2022-03-10 优先队列 找第k个数字,合并k个升序链表

          本文链接:https://www.haomeiwen.com/subject/znkfdrtx.html