Find K Closest Elements
Given a sorted array 'A' of length 'N', and two integers 'K' and 'X', your task is to find 'K' integers from the array closest to 'X'. If two integers are at the same distance, prefer the smaller one.
Input:
T
N K X
A[0] A[1] ... A[N-1]
Output:
B[0] B[1] ... B[K-1]
Example:
Input:
1
8 3 5
1 2 3 4 5 6 7 8
Output:
4 5 6
Constraints:
- 1 <= T <= 5
- 1 <= N, K <= 5000
- 1 <= A[i], X <= 10^6
Note:
An integer 'a' is closer to 'X' than an integer 'b' if: |a - X| < |b - X|
or (|a - X| == |b - X| and a < b)
.
Hope this C++ code will help you :)
#define pair pair<int,int> class cmp{ public: bool operator()(pair a, pair b){ if(a.first!=b.first)return a.first>b.first; return a.second>b.second; } }; class Solut...read more
vector<int> closestelements(vector<int> &a , int k , int x){
int left=0;
int right=a.size()-1;
while(left<right){
int mid = left + (right - left) / 2;
if (A[mid] == X) { left = mid; break;
} else if (A[mi...read more
Top Trilogy Innovations Software Developer Intern interview questions & answers
Popular interview questions of Software Developer Intern
Reviews
Interviews
Salaries
Users/Month