Title Description ：

No. found in unsorted array  k  Largest elements . Please note that , What you need to find is the first k Largest elements , It's not number one k Different elements .

Examples 1

input : [3,2,1,5,6,4] and k = 2
output : 5

Examples 2:

input : [3,2,3,1,2,4,5,5,6] and k = 4
output : 4

This is the question , Thinking under transformation , The first K The biggest element is the front K The smallest of the elements .

* Build a small root heap , The size of the heap is K
* 1） When the size of the heap is less than K When , Add new elements to it in turn
* 2） When the size of the heap =k Time , Next time each element is added , Then the top elements of the heap will be changed first （ Minimum element ） Throw out ,
* Finally scan the list , Then the heap top element （ minimum value ） For the first time K Big elements package leetcode; import java.util.Comparator;
import java.util.PriorityQueue; /** * Created by szh on 2020/6/19. * * @author
szh */ public class TOPK_N { public int findKthLargest(int[] nums, int k) { if
(k > nums.length || k == 0) { return -1; } PriorityQueue<Integer> priorityQueue
= new PriorityQueue<>(k, new Comparator<Integer>() { @Override public int
compare(Integer o1, Integer o2) { return -o2.compareTo(o1); } }); for (int i =
0; i < nums.length; i++) { int tmp = nums[i]; if (priorityQueue.size() < k) {
priorityQueue.offer(tmp); } else if (priorityQueue.peek() < tmp) {
priorityQueue.poll(); priorityQueue.offer(tmp); } } // while
(priorityQueue.size() != 1) { // //System.out.println(priorityQueue.poll()); //
priorityQueue.poll(); // } return priorityQueue.poll(); } public static void
main(String[] args) { TOPK_N topk_n = new TOPK_N(); int result_1 =
topk_n.findKthLargest(new int[]{1, 2, 4, 3, 2, 2, 2, 2, 2}, 5);
System.out.println(result_1);
System.out.println("------------------------------");
System.out.println("------------------------------");
System.out.println("------------------------------"); int result_2 =
topk_n.findKthLargest(new int[]{1, 2, 4, 3, 2, 2, 2, 2, 2}, 2);
System.out.println(result_2);
System.out.println("------------------------------");
System.out.println("------------------------------");
System.out.println("------------------------------"); int result_3 =
topk_n.findKthLargest(new int[]{1, 2, 4, 3, 5, 6, 7, 8, 9}, 4);
System.out.println(result_3); } }

Technology
Daily Recommendation
views 2