
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find K Closest Elements in C++
Suppose we have a sorted array, two integers k and x are also given, we have to find the k closest elements to x in that array. The result should be sorted in increasing order. If there is a tie, the smaller elements are always preferred. So if the input is like [1,2,3,4,5] and k = 4, x = 3, then output will be [1,2,3,4]
To solve this, we will follow these steps −
- Make an array called ans
- set low := 0, high := size of the array – k
- while low < high
- mid := low + (high - low) /2
- if x – arr[mid] > arr[mid + k] – x, then low := mid + 1, otherwise high := mid
- for i in range low to low + k
- insert arr[i] into ans array
- return ans
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { vector <int> ans; int low = 0; int high = arr.size() - k; while(low < high){ int mid = low + (high - low)/2; if(x - arr[mid] > arr[mid + k] - x){ low = mid + 1; } else high = mid; } for(int i = low ; i < low + k ; i++)ans.push_back(arr[i]); return ans; } }; main(){ Solution ob; vector<int> v = {1,2,3,4,5}; print_vector(ob.findClosestElements(v, 4, 3)); }
Input
[1,2,3,4,5] 4 3
Output
[1,2,3,4]
- Related Articles
- Find k closest elements to a given value in C++
- Find K Closest Points to the Origin in C++
- Program to find three unique elements from list whose sum is closest to k Python
- Find k closest numbers in an unsorted array in C++
- Find three closest elements from given three sorted arrays in C++
- Bitwise AND of sub-array closest to K in C++
- Program to find k where k elements have value at least k in Python
- Find the Closest Palindrome in C++
- Find closest number in array in C++
- Python program to find Non-K distant elements
- Find smallest range containing elements from k lists in C++
- Find closest index of array in JavaScript
- Find k maximum elements of array in original order in C++
- Program to find minimum amplitude after deleting K elements in Python
- Find the k smallest numbers after deleting given elements in C++

Advertisements