zoukankan      html  css  js  c++  java
  • 求k个最小元素, 华为

    Java 大根堆,维护k个最小的元素,时间复杂度O(NlogK)。

    import java.util.*;
    public class Main {
        public static void main(String[] args){
            Scanner sc = new Scanner(System.in);
            while(sc.hasNext()){
                int n = sc.nextInt(), k = sc.nextInt();
                PriorityQueue<Integer> q = new PriorityQueue<>(Collections.reverseOrder());
                for(int i=0; i < n; i++) {
                    int t = sc.nextInt();
                    if(q.isEmpty() || q.size() < k) q.offer(t);
                    else {
                        int min = q.peek();
                        if(t < min) {
                            q.poll();
                            q.offer(t);
                        }
                    }
                }
                ArrayList<Integer> res = new ArrayList<>();
                while(!q.isEmpty()) res.add(q.poll());
                for(int i=k-1; i > 0; i--) 
                    System.out.print(res.get(i) + " ");
                System.out.println(res.get(0));
            }
        }
    }
    
  • 相关阅读:
    JUC学习
    java反射学习
    JSON入门学习
    redis
    NoSQ学习
    手写Lockl锁
    MapReduce过程
    scala学习
    idea jetty 配置
    java 基础--理论知识
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13264065.html
Copyright © 2011-2022 走看看