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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013554860/article/details/83027503

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

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        vector<int> 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;
    }
};

阅读更多
换一批

没有更多推荐了,返回首页