LeetCode | 658. Find K Closest Elements

题目

Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

An integer a is closer to x than an integer b if:

  • |a - x| < |b - x|, or
  • |a - x| == |b - x| and a < b

Example 1:

Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]

Example 2:

Input: arr = [1,2,3,4,5], k = 4, x = -1
Output: [1,2,3,4]

Constraints:

  • 1 <= k <= arr.length
  • 1 <= arr.length <= 104
  • arr is sorted in ascending order.
  • -10^4 <= arr[i], x <= 10^4

代码

class Solution {
public:
    int findX(vector<int>& arr, int x) {
        int low = 0, high = arr.size() - 1;
        while(low < high)
        {
            int mid = (low + high) / 2;
            if(arr[mid] == x)
                return mid;
            if(arr[mid] < x)
                low = mid + 1;
            else
                high = mid;
        }
        if(arr[high] > x)
        {
            if(high > 0 && x - arr[high-1] < arr[high] - x)
                return high - 1;
        }
        return high;
    }
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        vector<int> res;
        if(arr.size() < 1)
            return res;
        if(x <= arr[0])
        {
            res = vector(arr.begin(), arr.begin()+k);
            return res;
        }
        if(x >= arr[arr.size() - 1])
        {
            res = vector(arr.end()-k, arr.end());
            return res;
        }
        int idx = findX(arr, x), startIdx = idx, endIdx = idx;
        for(int j = 1; j < k && startIdx >= 0 && endIdx < arr.size(); j++)
        {
            if(startIdx == 0)
            {
                endIdx++;
            }
            else if(endIdx == arr.size() - 1)
            {
                startIdx--;
            }
            else
            {
                if(x - arr[startIdx - 1] <= arr[endIdx + 1] - x)
                {
                    startIdx--;
                }
                else
                {
                    endIdx++;
                }
            }
        }
            
        //cout << idx << " " << startIdx << " " << endIdx << endl;
        res = vector(arr.begin()+startIdx, arr.begin()+endIdx+1);
        return res;
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值