<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:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int pos = -1;
        vector<int> new_arr(arr.size() + 4);
        new_arr[0] = -200000;
        new_arr[1] = -100000;
        for(int i = 0; i < arr.size(); i++) {
            new_arr[i+2] = arr[i];
        }
        new_arr[arr.size()+2] = 100000;
        new_arr[arr.size()+3] = 200000;

        int l = 0, r = arr.size()+1, m;
        while(l < r) {
            m = (l + r)/2;
            if(new_arr[m] == x) {
                pos = m;
                break;
            }

            if(new_arr[m] > x) r = m - 1;
            else l = m + 1;
        }

        if(pos == -1) {
            if(x > new_arr[l]) {
                if((x - new_arr[l]) <= (new_arr[l+1] - x)) pos = l;
                else pos = l+1;
            } else { 
                if((x - new_arr[l-1]) <= (new_arr[l] - x)) pos = l-1;
                else pos = l;
            }
        }
        l = pos - 1;
        r = pos + 1;

        vector<int> ans;
        ans.emplace_back(new_arr[pos]);
        int ldiff = 0, rdiff = 0;
        while(ans.size() < k) {
            ldiff = x - new_arr[l];
            rdiff = new_arr[r] - x;
            if(ldiff <= rdiff) {
                ans.emplace_back(new_arr[l--]);
            } else {
                ans.emplace_back(new_arr[r++]);
            }
        }
        sort(ans.begin(), ans.end());

        return ans;
    }
};
36400