<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 {
  vector<vector<bool>> visited;
  int m, n;

public:
  int lowerBound(vector<int>& v, int target){
    int low = 0, high = v.size()-1, mid, ans = -1;
    while(low<=high){
      mid = low + (high-low)/2;
      if(v[mid]>=target){
        ans = mid;
        high = mid-1;
      } else {
        low = mid+1;
      }
    }
    return ans;
  }

  vector<int> findClosestElements(vector<int>& arr, int k, int x) {
    int n = arr.size();
    vector<int> ans;
    int lb = lowerBound(arr, x);
    if(lb == -1){
      lb = n-1;
    }
    int i = lb-1, j = lb, cnt = k;
    int leftIndex, rightIndex;
    if(lb==0){
      leftIndex = lb; rightIndex=lb;
    } else {
      (abs(x-arr[i])<=abs(arr[j]-x)) ? (leftIndex=i, rightIndex=i) :  (leftIndex=j, rightIndex=j);
    }
    while(i>=0 && j<=n-1 && cnt>0){
      if(abs(x-arr[i]) <= abs(arr[j]-x)){
        leftIndex=i; i-=1;
      } else {
        rightIndex=j;j+=1;
      }
      cnt-=1;
    }
    while(cnt>0 && i>=0){
      leftIndex=i; i-=1; cnt-=1;
    }
    while(cnt>0 && j<=n-1){
      rightIndex=j; j+=1; cnt -=1;
    }
    // cout<<leftIndex<<' '<<rightIndex<<endl;
    for(int index=leftIndex;index<=rightIndex;index++)ans.push_back(arr[index]);
    return ans;
  }

};

34400