File tree 1 file changed +64
-0
lines changed
Course 2 - Data Structures in JAVA/Lecture 21 - Priority Queues II
1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Given an array A of random integers and an integer k, find and return the kth largest element in the array.
3
+ Note: Try to do this question in less than O(N * logN) time.
4
+
5
+ Input Format :
6
+ The first line of input contains an integer, that denotes the value of the size of the array. Let us denote it with the symbol N.
7
+ The following line contains N space separated integers, that denote the value of the elements of the array.
8
+ The following contains an integer, that denotes the value of k.
9
+
10
+ Output Format :
11
+ The first and only line of output contains the kth largest element
12
+
13
+ Constraints :
14
+ 1 <= N, Ai, k <= 10^5
15
+ Time Limit: 1 sec
16
+
17
+ Sample Input 1 :
18
+ 6
19
+ 9 4 8 7 11 3
20
+ 2
21
+ Sample Output 1 :
22
+ 9
23
+
24
+ Sample Input 2 :
25
+ 8
26
+ 2 6 10 11 13 4 1 20
27
+ 4
28
+ Sample Output 2 :
29
+ 10
30
+ */
31
+
32
+ import java.util.*;
33
+ public class Solution {
34
+
35
+ public static int kthLargest(int n, int[] input, int k) {
36
+ // Write your code here
37
+ PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
38
+ for(int i=0;i<k;i++)
39
+ {
40
+ pq.add(input[i]);
41
+ }
42
+
43
+ for(int i=k;i<input.length;i++)
44
+ {
45
+ int minVal=pq.peek();
46
+ if(minVal<input[i])
47
+ minVal=input[i];
48
+ if(minVal!=pq.peek())
49
+ {
50
+ pq.poll();
51
+ pq.add(minVal);
52
+ }
53
+ }
54
+
55
+ int minVal=Integer.MAX_VALUE;
56
+ while(!pq.isEmpty())
57
+ {
58
+ int check=pq.poll();
59
+ if(check<minVal)
60
+ minVal=check;
61
+ }
62
+ return minVal;
63
+ }
64
+ }
You can’t perform that action at this time.
0 commit comments