[LeetCode] 658. Find K Closest Elements

本文介绍了一种高效算法,用于从已排序数组中找到与目标值最接近的K个数字。通过调整二分查找,快速定位目标值附近的元素,并确保结果按升序排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: https://leetcode.com/problems/find-k-closest-elements/description/

Description

Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

Example 1:

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

Example 2:

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

Note:
1. The value k is positive and will always be smaller than the length of the sorted array.
2. Length of the given array is positive and will not exceed 104
3. Absolute value of elements in the array and x will not exceed 104

解题思路

题意为从给定有序数组arr中找到与x最接近的k个数字。有序数组找指定数,首先想到的就是用二分查找来确定大致位置。二分查找算法通过修改一点点代码可以有很多不同种的预期值,我在这道题中使用的是,查找最后一个小于等于x的元素下标,从该下标开始向左向右搜索更接近该值的数,用两个变量leftright来表示边界下标,最终获得需要的区间为[left + 1, right)

另外,由于二分查找是找最后一个小于等于x的数字,若x = -1arr = [1, 2, 3],即数组中没有比其更小的数字时,搜索得到的下标将为-1,需要调整一下边界值,令right = 1即可。

时间复杂度为 O(logn + k),空间复杂度为 O(1)

Code

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int left = 0, right = arr.size() - 1;
        int middle;

        while (left <= right) {
            middle = (left + right) >> 1;
            if (x < arr[middle]) {
                right = middle - 1;
            } else {
                left = middle + 1;
            }
        }

        if (right < 0) right = 1;
        left = right - 1;

        while (k-- > 0) {
            if (left >= 0 && right < arr.size()) {
                if ((x - arr[left]) <= (arr[right] - x)) {
                    left--;
                } else {
                    right++;
                }
            } else if (left >= 0) {
                left--;
            } else {
                right++;
            }
        }    

        return vector<int>(arr.begin() + left + 1, arr.begin() + right);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值