zoukankan      html  css  js  c++  java
  • leetcode (堆->simple)703,1046,前k大/小数

    703

    第K大

    class KthLargest {
    
        private PriorityQueue<Integer> heap ;
        
        private int k;
    
        public KthLargest(int k, int[] nums) {
    heap = new PriorityQueue<>(k,(k1,k2)->k1.compareTo(k2));
            this.k = k;
            for (int i = 0; i < nums.length; i++) {
                if (i < k){
                    heap.add(nums[i]);
                }else {
                    if (nums[i] >= heap.peek()){
                        heap.poll();
                        heap.add(nums[i]);
                    }
                }
            }
        }
        
        public int add(int val) {
            if (heap.size() < k){
                heap.add(val);
            } else if (val >= heap.peek()){
                heap.poll();
                heap.add(val);
            }
            return heap.peek();
        }
    }
    
    /**
     * Your KthLargest object will be instantiated and called as such:
     * KthLargest obj = new KthLargest(k, nums);
     * int param_1 = obj.add(val);
     */

    1046

    也是用堆的特性来做

            PriorityQueue<Integer> heap = new PriorityQueue<>((k1,k2)->k2.compareTo(k1));
            for (int i = 0; i < stones.length; i++) {
                heap.offer(stones[i]);
            }
    
            while (heap.size() > 1){
                Integer x1 = heap.poll();
                Integer x2 = heap.poll();
                if (x1 != x2){
                    heap.offer(Math.abs(x1-x2));
                }
            }
            if (heap.isEmpty()){
                return 0;
            }
    
            return heap.poll();

    前大/小K 个数

        public static int[] getLeastNumbers(int[] arr,int k) {
            if (k ==0 || arr.length == 0){
                return new int[0];
            }
            PriorityQueue<Integer> heap = new PriorityQueue<>((k1,k2)->k2.compareTo(k1));
            for (int i = 0; i < arr.length; i++) {
                if (i < k){
                    heap.offer(arr[i]);
                }else {
                    if (arr[i] < heap.peek()){
                        heap.poll();
                        heap.offer(arr[i]);
                    }
                }
            }
            int size = heap.size(),ks = 0;
            int[] result = new int[size];
            while (ks<size){
                result[ks++] = heap.poll();
            }
    
            return result;
        }
  • 相关阅读:
    pytest
    pytest 跳过测试用例 skip
    pytest
    pytest -allure标记用例级别severity
    pytest-
    pytest-分布式执行(pytest-xdist)
    4、win10搭建easy-mock平台
    pandas日期缺失,空值填充方法
    Pandas拼接操作(concat,merge,join和append)的区别
    关于docker容器和镜像的区别
  • 原文地址:https://www.cnblogs.com/hetutu-5238/p/14345189.html
Copyright © 2011-2022 走看看