**Leetcode 658. Find K Closest Elements

https://leetcode.com/problems/find-k-closest-elements/description/

双指针


class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int pos = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
        if (pos - 1 >= 0 && abs(arr[pos-1] - x) < abs(arr[pos] - x) ) {
            pos--;
        }
        vector<int> ret;
        ret.push_back(arr[pos]);
        k--;
        int left = pos-1, right = pos+1;
        while (k--) {
            // int diff = INT_MAX;
            if (left < 0) {
                ret.push_back(arr[right]);
                right++;
                continue;
            }
            if (right >= arr.size()) {
                ret.push_back(arr[left--]);
                continue;
            }
            
            if (abs(arr[left] - x) <= abs(arr[right] - x) ) {
                ret.push_back( arr[left--] );
            } else {
                ret.push_back( arr[right++] );
            }
        }
        sort(ret.begin(), ret.end());
        return ret;
    }
};


猜你喜欢

转载自blog.csdn.net/u011026968/article/details/80920893