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

<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>

<ul>
	<li><code>|a - x| &lt; |b - x|</code>, or</li>
	<li><code>|a - x| == |b - x|</code> and <code>a &lt; b</code></li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> arr = [1,2,3,4,5], k = 4, x = 3
<strong>Output:</strong> [1,2,3,4]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> arr = [1,2,3,4,5], k = 4, x = -1
<strong>Output:</strong> [1,2,3,4]
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= k &lt;= arr.length</code></li>
	<li><code>1 &lt;= arr.length &lt;= 10<sup>4</sup></code></li>
	<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>
	<li><code>-10<sup>4</sup> &lt;= arr[i], x &lt;= 10<sup>4</sup></code></li>
</ul>

class Custom_comparator{

    public: 
        bool operator()(pair<int, int> i, pair<int, int> j){
            if (i.first > j.first) return true;
            else if (i.first < j.first) return false;
            else return i.second > j.second;
        }
    
};

class Solution {
public:
    int binary_search(int l, int r, int value, vector<int> & arr){
        int mid = (l + r) / 2;
        if (l == r) return l;
        if (arr[mid] == value) return mid;
        if (arr[mid] < value) return binary_search(mid+1, r, value, arr);
        return binary_search(l, mid, value, arr);
    } 
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        vector<int> ans;
        int n = arr.size();
        priority_queue<pair<int, int>, vector<pair<int, int> >, Custom_comparator > q;
        int id = binary_search(0, n-1, x, arr); 
        for (int i = id; i >= 0 && i >= id-k; i--) q.push({abs(arr[i] - x), arr[i]});
        for (int i = id+1; i < n && i <= id+k; i++) q.push({abs(arr[i] - x), arr[i]});
        for (int i = 0; i < k; i++){
            ans.push_back(q.top().second);
            q.pop();
        }
        sort(ans.begin(), ans.end());
        return ans;
    }
};

39400