Find K Closest Elements

# 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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值