-
Notifications
You must be signed in to change notification settings - Fork 617
/
Copy pathK_largest_element.cpp
99 lines (81 loc) · 2.65 KB
/
K_largest_element.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//CPP Code For Finding K Largest Element In An Array In Ascending Order.
/*
Approach
========
We can efficiently implement this using a Min-Heap.
1. We will create a min heap.
2. We will traverse through all the elements of the array
and insert them into the min heap
3. We are using a min heap and inverting the numbers, i.e. inserting -1*number.
3. We are maintaining the heap at the size of k always.
4. Pop extra elements if the size becomes greater than k.
5. When we reach the end of the array then we will
print the value and pop the heap top till it becomes empty.
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int i, n, k;
vector<int> V;
cout << "Enter the size of the array :";
cin >> n;
cout << "\nEnter the elements of the array :";
for (i = 0; i < n; i++)
{
int num;
cin >> num;
V.push_back(num);
}
cout << "\nEnter the value of K :";
cin >> k;
priority_queue<int> minHeap;
for (auto v : V)
{
minHeap.push(-v);
if (minHeap.size() > k)
{
minHeap.pop();
}
}
cout << "\nK largest array element in ascending order are : ";
while (!minHeap.empty())
{
cout << -minHeap.top() << ", ";
minHeap.pop();
}
return 0;
}
/*
Time-Complexity: O(nlog(k))
where n => size of the array , k => the number of largest elements to find
Sample Input/Output
=====================
Sample Input 1 :
5
9 8 7 6 5
3
Sample Output 1 :
Enter the size of the array :
Enter the elements of the array :
Enter the value of K :
K largest array element in ascending order are : 7, 8, 9,
Sample Input 2 :
7
19 8 17 6 15 0 3
4
Sample Output 2 :
Enter the size of the array :
Enter the elements of the array :
Enter the value of K :
K largest array element in ascending order are : 8, 15, 17, 18,
Sample Input 3 :
6
7 10 4 3 20 15
3
Sample Output 3 :
Enter the size of the array :
Enter the elements of the array :
Enter the value of K :
K largest array element in ascending order are : 10, 15, 20,
*/