Leetcode|Find K Closest Elements

时间:2022-05-06
本文章向大家介绍Leetcode|Find K Closest Elements,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

01

题目

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.

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

Input: [1,2,3,4,5], k=4, x=-1Output: [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

题目的意思是求出与x最相近的k个元素

02

分析

考虑两种特殊情况:

  1. x 小于等于 arr[0]
  2. x 大于等于 arr[-1]

然后,考虑一般情况,这时与x的距离,分布情况为:与x的距离先降为0,然后再逐渐增大,所以里面又有两种可能:

  1. 距离等于0的元素个数大于或等于k
  2. 距离等于0的元素个数小于k,这种情况求解,稍微复杂,需要二分动态查找。

以上分析的时间复杂度为O(n),空间复杂度为O(1)。

03

python代码


"""
arr: array wanted to search
k : k numbers nearest to x
x: goal center point
assert:
  1. arr is sorted
  2. ele in arr is integer
"""
def findKNearestToX(arr=[1,3,5],k=2,x=0):
    # x less or equal than arr[0]
    if x <= arr[0]:
        return arr[:k]
    # x bigger or equal than arr[-1]
    if x >= arr[-1]:
        return arr[-k:]
    # ordinary cases: at least one zero,
    # distance distribution: decline-->0-->rise
    hi=0
    zerolen=0
    for i,item in enumerate(arr):
        item = abs(item-x)
        if item==0:
            hi=i
            zerolen+=1
            if zerolen == k:
                return arr[hi-zerolen+1:hi+1]
    # here shows: number of zero chunk is less than k
    # then it needs to dynamic binary search
    lo = hi - zerolen+1
    curlen = zerolen
    while curlen < k:
        if lo > 0 and abs(arr[lo-1]-x) <= abs(arr[hi+1]-x):
            lo-=1
        elif hi < len(arr):
            hi+=1
        curlen+=1
    return arr[lo:hi+1]

#单元test
#1
kNearest = findKNearestToX(arr=[1,3,5],k=2,x=0)
#2
kNearest = findKNearestToX(arr=[1,3,5],k=2,x=5)
#3
#3-1
kNearest = findKNearestToX(arr=[1,3,3,3,5],k=2,x=3)
#3-2
kNearest = findKNearestToX(arr=[1,3,4,5],k=3,x=3)
#3-3
kNearest = findKNearestToX(arr=[-1,3,4,4],k=3,x=3)
print(kNearest)