leetcode658+有序数组找出距离数字x最近的k个数字

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

class Solution {
public:
    vector findClosestElements(vector& arr, int k, int x) {
        vector res = arr;
        while (res.size()>k) {
            int first =0, last = res.size()-1;
            if(x-res.front() <= res.back()-x){
                res.pop_back();
            }
            else{
                res.erase(res.begin());
            }
        }
        return res;
    }
};

leetcode658+有序数组找出距离数字x最近的k个数字_第1张图片

你可能感兴趣的:(Leetcode)