Find K Closest Elements

本文介绍了一种在已排序数组中查找与指定数值最接近的k个元素的算法,并提供了两种解决方案:一种使用双指针从两端逼近目标,另一种利用二分搜索提高效率。文章附带了C++和Python实现代码。

# Find K Closest Elements

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:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 104
Absolute value of elements in the array and x will not exceed 104

Solution 1

Find the k closest elements to x <=> remove the (n-k) elements farthest from x. So using two points to point to left, right, then every time remove a further element, util k elements left.
Refer to http://www.cnblogs.com/grandyang/p/7519466.html

    // C++
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
       int n = arr.size();
       if (n <= 0 || k > n) {
           return vector<int>();
       }

       int left = 0;
       int right = n - 1;
       while ((right - left + 1) > k) {
           if (x - arr[left] <= arr[right] - x) {
               --right;
           } else {
               ++left;
           }
       }
       return vector<int>(arr.begin() + left, arr.begin() + left + k);
   }

    """ Python """
    def findClosestElements(self, arr, k, x):
       """
       :type arr: List[int]
       :type k: int
       :type x: int
       :rtype: List[int]
       """
       n = len(arr)
       if n <= 0 or k > n:
           return []

       # in python, don't need define, use variable directly
       start = 0
       end = n - 1
       while (end - start + 1) > k:
           if x - arr[start] <= arr[end] - x:
               end -= 1
           else:
               start += 1

       return arr[start: start + k]

Time Complexity: O(n - k)
Space Complexity: O(1)

Solution 2

Since the problem has a sorted array, it’s easy to consider binary search.
Step 1: find the first element who is less than x, return its index
Step 2: beginning with the index, comparing elements on both sides, add the closer element one by one, util to get k elements

    // C++

   """ python """

Solution 3

TODO

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值