Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

An integer a is closer to x than an integer b if:


	|a - x| &lt; |b - x|, or
	|a - x| == |b - x| and a &lt; b


&nbsp;
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Example 2:
Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]

&nbsp;
Constraints:


	1 &lt;= k &lt;= arr.length
	1 &lt;= arr.length &lt;= 104
	arr is sorted in ascending order.
	-104 &lt;= arr[i], x &lt;= 104


class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        
        def sorted_distance(value, static_input = x):
            return abs(value - static_input)
        
        distances = []
        result = []
        heapq.heapify(distances)
        
        for l,v in enumerate(arr):
            distances.append((l, sorted_distance(value = v)))
        
        for i in heapq.nsmallest(k, distances, key = lambda x: x[1]):
            result.append(arr[i[0]])
        
        result.sort()
        return result
            
            
class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
    List<Integer> result = new ArrayList<>();

    int low = 0, high = arr.length -1;

    while(high - low >= k){
        if(Math.abs(arr[low] - x) > Math.abs(arr[high] - x))
            low++;
        else
            high--;
    }

    for(int i = low; i <= high; i++)
        result.add(arr[i]);

    return result;
}
}
class Solution {
public:
    static bool cmp(pair<int,int>&p1,pair<int,int>&p2)
    {
        if(p1.first==p2.first)  //both having equal abs diff
        {
            return p1.second<p2.second;
        }
        return p1.first<p2.first;
    }
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        
        vector<pair<int,int>>v;    //abs diff , ele
        
        for(int i=0;i<arr.size();i++)
        {
            v.push_back(make_pair(abs(arr[i]-x),arr[i]));
        }
        
        sort(v.begin(),v.end(),cmp);
        vector<int>ans;
        for(int i=0;i<k;i++)
        {
            ans.push_back(v[i].second);
        }
        sort(ans.begin(),ans.end());
        return ans;   
    }
};
var findClosestElements = function(arr, k, x) {
	const result = [...arr];

	while (result.length > k) {
		const start = result[0];
		const end = result.at(-1);

		x - start <= end - x 
			? result.pop() 
			: result.shift();
	}
	return result;
};
Find K Closest Elements