1+ /*
2+ author:gulshan yadav
3+ email: gulshany01@gmail.com
4+ date: 21-July-2021
5+ */
6+ #include < iostream>
7+ #include < bits/stdc++.h>
8+ using namespace std ;
9+
10+
11+ // this is the naive approach
12+ // Time : O(NK)
13+ // Aux : O(N)
14+ void kClosest (int arr[], int num, int k,int x ){
15+
16+ // iter to the kth time
17+ bool visited[num] = {false };
18+ for (int i = 0 ; i< k; i++){
19+
20+
21+ int minDiff = INT_MAX;
22+ int minInd;
23+ for (int j = 0 ; j< num; j++){
24+ if ((visited[j] == false ) && (abs (arr[j]-x) <= minDiff)){
25+ minDiff = abs (arr[j]-x);
26+ minInd = j;
27+
28+ }
29+ }
30+ // print the value
31+ cout << arr[minInd]<<" " ;
32+ visited[minInd] = true ;
33+ }
34+ }
35+
36+
37+ // efficieint solution
38+ void kClosest2 (int arr[], int num, int k, int x){
39+ // create a max heap;
40+ priority_queue<pair<int , int >> pq;
41+
42+ for (int i = 0 ; i< k; i++){
43+ pq.push ({abs (arr[i]-x), i});
44+
45+ }
46+
47+ for (int i = k; i< num; i++){
48+ int minDiff = abs (arr[i]-x);
49+ if (pq.top ().first > minDiff){
50+ pq.pop ();
51+ pq.push ({minDiff, i});
52+ }
53+ }
54+ // print the value
55+
56+ while (pq.empty () == false ){
57+ cout << arr[pq.top ().second ]<< " " ;
58+ pq.pop ();
59+ }
60+
61+ }
62+
63+ int main (){
64+ int num;
65+ cin >> num;
66+ int arr[num];
67+ for (int i =0 ; i< num; i++){
68+ cin >> arr[i];
69+ }
70+ int k, x;
71+ cin >> k>> x;
72+ kClosest (arr, num, k, x);
73+ cout << endl;
74+ kClosest2 (arr, num, k, x);
75+ return 0 ;
76+ }
0 commit comments