<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) {
        if(k==arr.size())
            return arr;
        vector<int> result(k);
        int start = 0;
        int end = arr.size()-1;
        int floorIndex = -1;
        while(start<=end){
            int mid = (start + end)/2;
            if(arr[mid]<x)
                start = mid + 1;
            else if(arr[mid]>x)
                end = mid - 1;
            else{
                floorIndex = mid;
                break;
            }
        }
        if(floorIndex==-1){
            if(start>arr.size()-1)
                floorIndex = end;
            else if(end<0)
                floorIndex = start;
            else{
                if((abs(arr[start]-x)<abs(arr[end]-x)) || (abs(arr[start]-x)==abs(arr[end]-x) && arr[start]<arr[end]))
                    floorIndex = start;
                else 
                    floorIndex = end;
            }
        }
        int windowStart = -1;
        int windowEnd = -1;
        if((floorIndex - k +1) < 0){
            windowStart = 0;
            //windowEnd = k-1;
        }
        else{
            windowStart = floorIndex - k + 1;
            //windowEnd = windowStart + k - 1;
        }
        windowEnd = windowStart + k - 1;
        while((windowEnd+1)<arr.size()){
            if(abs(arr[windowEnd+1]-x)<abs(arr[windowStart]-x)){
                windowStart++;
                windowEnd++;
            }
            else
                break;
        }


        int index = 0;
        while(windowStart<=windowEnd){
            result[index] = arr[windowStart];
            windowStart++;
            index++;
        }
        return result;
    }
};
33600