Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,970 questions

51,912 answers

573 users

How to find the K largest element in a list with Java

1 Answer

0 votes
import java.util.List;
import java.util.Arrays;
import java.util.PriorityQueue;

public class MyClass {
    public static int findKLargest(List<Integer> lst, int K) {
        if (lst == null || lst.size() < K) {
            return -1;
        }
 
        PriorityQueue<Integer> pq = new PriorityQueue<>(lst.subList(0, K));
 
        for (int i = K; i < lst.size(); i++) {
            if (lst.get(i) > pq.peek()) {
                pq.poll();
                pq.add(lst.get(i));
            }
        }
 
        return pq.peek();
    }
 
    public static void main(String args[]) {
        List<Integer> lst = Arrays.asList(100, 88, 98, 80, 50, 12, 35, 70, 60, 97, 85, 89);
        int K = 4;
 
        System.out.println(findKLargest(lst, K));
    }
}




/*
run:

89

*/

 



answered May 13, 2022 by avibootz

Related questions

1 answer 117 views
1 answer 116 views
2 answers 206 views
2 answers 97 views
...