<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>

import heapq
class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        '''
        because it is sorted, I think it would be some kind of binary search

        human approach:
        find x in the array
        starting from x, find k - 1 integers closest to x. k - 1 because x is usually included with response
        get x - 1 num, x + 1, x - 2, x + 2, etc...
        
        keep doing that until we have k elements

        cases:
            if k > size of arr, return arr
            if x is smaller than smallest elem in arr. get first k elements
            if x bigger than biggest elem in arr. return last k elements
            if x is in the array
                left and right pointer
                while left > 0
                    add left to res
                    decrement left
                while right < len(arr):
                    add right to res
                    inc right
            return sorted(res)
        '''
        if k > len(arr):
            return arr
        if x < arr[0]:
            return arr[:k]
        if x > arr[-1]:
            return arr[-k:]
        res = []
        heap = []
        while arr:
            elem = arr.pop()
            dist = abs(elem - x)
            heapq.heappush(heap, (dist, elem))
        while len(res) != k:
            dist, elem = heapq.heappop(heap)
            res.append(elem)
        return sorted(res)
18500