<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:
    // int binarySearch(vector<int>& arr, int x) {
    //     int l = 0, h = arr.size()-1;
    //     while (l <= h) {
    //         int mid = l + (h-l)/2;
    //         if (arr[mid] == x) {
    //             return mid+1;
    //         } else if(arr[mid]>x){
    //             h = mid-1;
    //         } else{
    //             l = mid+1;
    //         }
    //     }
    //     return -1;
    // }

    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        // int size = index(arr, k, x);
        
        // int size = binarySearch(arr, x)+1;
        // if(size==2) return arr;
        // vector<int> a;
        // cout<<size<<endl;
        // if(size>1){
        //     for (int z = 0; z < size; z++) {
        //         a.push_back(arr[z]);
        //     }
        // }
        // else{
        //     for(int z = 0; z<k; z++){
        //         a.push_back(arr[z]);
        //     }
        // }
        // return a;
        //M-1 by Lakshya bhaiya
        vector<int> diff, ans;
        for(int i = 0; i<arr.size(); i++){
            int curr_diff = abs(arr[i]-x);
            diff.push_back(curr_diff);
        }
        int l = 0, h = diff.size()-1;
        while(h-l+1>k){
            if(diff[l]>diff[h]){
                l++;
            }
            else{
                h--;
            }
        }
        for(int i = l; i<=h; i++){
            ans.push_back(arr[i]);
        }
        return ans;
    }
};
//case-1 -> arr[mid] == x ans->store;
//case-2 -> abs(arr[mid]-arr[l])<=x ans -> store 
37500