<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 Solution {
public:
    typedef pair<int, int> pp;
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int n = arr.size();
        vector<int> result(k);
        // case1 : if x is less than the first element of array then first k elements will be the answer.
        if(x < arr[0]){
            for(int i=0; i<k; i++){
                result[i] = arr[i];
            }
        }
        
        // case2 : if x is greater than the last element of the array then last k elements will be the answer.
        if(x > arr[n-1]){
            for(int i=0; i<k; i++){
                result[i] = arr[n-1-i];
            }
        }
        
        // case3 : 
        priority_queue<pp, vector<pp>, greater<pp> > pq;
        for(int i=0; i<n; i++){
            pq.push({abs(x-arr[i]),arr[i]});
        }
        
        for(int i=0; i<k; i++){
            result[i] = pq.top().second;
            pq.pop();
        }
        sort(result.begin(), result.end());
        return result;
    }
};
40800