<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:
    std::vector<int> findClosestElements(std::vector<int> &nums, int k, int x)
    {
        std::vector<int> result;
        result.reserve(k);

        std::size_t n = nums.size();

        std::size_t i = 0;
        for (; i < n and nums[i] <= x; ++i)
            ;

        if (i == 0)
        {
            result.insert(result.end(), nums.begin(), nums.begin() + k);
        }
        else if (i == n)
        {
            result.insert(result.end(), nums.rbegin(), nums.rbegin() + k);
        }

        std::optional<std::size_t> left = i - 1;
        std::optional<std::size_t> right = i;

        while (result.size() < std::size_t(k))
        {
            if (left and right)
            {
                if (std::abs(nums[*left] - x) <= std::abs(nums[*right] - x))
                {
                    result.push_back(nums[*left]);
                    if (*left == 0)
                    {
                        left = std::nullopt;
                    }
                    else
                    {
                        --(*left);
                    }
                }
                else
                {
                    result.push_back(nums[*right]);
                    if (*right == n - 1)
                    {
                        right = std::nullopt;
                    }
                    else
                    {
                        ++(*right);
                    }
                }
            }
            else if (left)
            {
                result.push_back(nums[(*left)--]);
            }
            else if (right)
            {
                result.push_back(nums[(*right)++]);
            }
        }
        std::sort(result.begin(), result.end());

        return result;
    }
};
34700