zoukankan      html  css  js  c++  java
  • LeetCode414-第三大的数

    查找吧?

    1、因为题目要求是On的时间,所以排序肯定是不行的。、

    2、所以,重复的数字,都是同一个位置,所以可以去重。比存在的且不同的数字即可。

    3、用一个大小为3的堆来比吗?

     好像就是topK问题

        public static int thirdMax(int[] nums) {
    
            //去重
            Set<Integer> set = new HashSet<>();
    
            for(int i=0;i<nums.length;i++){
                set.add(nums[i]);
            }
    
            Iterator<Integer> iterator = set.iterator();
    
            int count = 0;
            PriorityQueue<Integer> queue = new PriorityQueue<>();
    
            //把数字都遍历一次,如果比queue里最小的元素大,就删掉queue里最小的元素,扔进queue
            //这样到最后,queue里面的元素,肯定都是比这些元素大的,这就是topK了
            while(iterator.hasNext()){
                int temp = iterator.next();
                if(count<3){
                    queue.add(temp);
                    count++;
                }else{
                    if(temp>queue.peek()){
                        queue.poll();
                        queue.add(temp);
                    }
                }
            }
    
            //麻烦一点,这样语意明确
            if(queue.size()>=3){
                return queue.poll();
            }else if (queue.size()==2){
                queue.poll();
                return queue.poll();
            }else {
                return queue.poll();
            }
    
    
        }

    答案里面,排序的运行时间好快

    最快的答案,不可取,一个个比较,如果K变多了呢?

  • 相关阅读:
    01-发送你的第一个请求
    postman使用
    java poi导出多sheet页
    base64加密解密
    Django crontab
    super().__init__()
    paramiko模块
    列表转json数据返回
    socket模块判断ip加端口的连通性
    登录拦截器
  • 原文地址:https://www.cnblogs.com/weizhibin1996/p/9647205.html
Copyright © 2011-2022 走看看