658. Find K Closest Elements

Description

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


Thoughts

  • A Straight-forward Binary Search Solution
    We can use binary search template to find the first number which is larger or equals to x, (say pivot).
    Then from pivot position and pivot - 1, we use the 2-pointers to find the closest numbers until we find k numbers.

    • Time complexity: O(logn): find the pivot + O(k):find the k numbers + O(klogk): sort the result array
    • Space complexity: O(k) for result array
  • Binary Search to find the left bound of the k window.
    The answer should be a k-length window. To get the k-length window we only need to find the start position (left bound of the k- window).
    We can use binary search to find the left bound. But we need to know how to define if the mid number is the start position or not.
    Think it this way: from position mid, we look at the k numbers after mid. So it’s arr[mid: mid + k + 1]. This window has k + 1 numbers in it. And either mid or mid + k is the one that we need to delete.

    • If x - arr[mid] > arr[mid + k] - x ⇒ for sure arr[mid] is not in the k numbers and all the numbers before mid should not be the start.
    • If x - arr[mid] <= arr[mid + k] - x ⇒ for sure arr[mid + k] is not in the k numbers and all the numbers after mid + k should not be the result. The left bound should be mid or someone before mid.
    • Time complexity: O(logn): find the left bound + O(k):find the k numbers
    • Space complexity: O(k) for result array

Code

leverage a regular binary search template

    def findClosestElements(self, arr: List[int]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值