简体   繁体   English

在差小于或等于K的数组中找到所有数字

[英]Find all the numbers in an array whoes difference less than or equal to K

I want to find two numbers A[i] and A[j] whose difference is less than or equal to K , I need to store index of such numbers in array L (Left) R (Right) and return L & R 我想找到两个数字A[i]A[j] ,它们的差小于或等于K ,我需要将这些数字的索引存储在数组L(左)R(右)中,并返回L&R

def fun(A, k): 
    n = len(A)
    l = 0
    r = n-1
    # traverse the array for the two elements 
    while l<r: 
        if (A[l] - A[r] <= n):
            return A[l],A[r]
        elif (A[l] - A[r] < n): 
            l += 1
        else: 
            r -= 1
    return 0

# Driver code to test above function 
A = [3.5,5,6,12,13] 
k = 1.7
print(fun(A, k))

Expected output: 预期产量:

L[0,0,1,3,3],R[1,2,2,4,4]

You should use itertools.combinations to get all possible combinations, then test their differences and append if needed. 您应该使用itertools.combinations获得所有可能的组合,然后测试它们之间的差异并在需要时附加。

from itertools import combinations

def fun(A, k):
    l, r = [], []
    for (x_idx, x_val), (y_idx, y_val) in combinations(enumerate(A), 2):
        if abs(x_val - y_val) <= k:
            l.append(x_idx)
            r.append(y_idx)
    return l, r

Test: 测试:

A = [3.5,5,6,12,13] 
k = 1.7
print(fun(A, k))
# ([0, 1, 3], [1, 2, 4])

Though it's not your expected output, I feel like your expected output may have a few errors according to your logic. 尽管这不是您的预期输出,但根据您的逻辑,我觉得您的预期输出可能会有一些错误。

An O(n log n) solution that exploits the ordering in your example A (if it's not ordered, you can always pay O(n log n) a second time to sort it, though preserving the original indices would likely make it not worth the complexity): 一个利用示例A的排序的O(n log n)解决方案(如果未排序,则始终可以第二次支付O(n log n)进行排序,尽管保留原始索引可能会使它不值得复杂度):

from bisect import bisect

def fun(A, k):
    # Add A.sort() if A not guaranteed to be sorted
    for l, x in enumerate(A):
        for r in range(l+1, bisect(A, x+k, l+1)):
            yield l, r

This uses the bisect.bisect function to find the end point for each start point in O(log n) time, making the overall cost O(n log n) . 这使用bisect.bisect函数O(log n)时间中找到每个起点的终点,从而使总成本为O(n log n) It doesn't even need to directly test most values against k , since bisect finds the end of the indices which meet the different criteria, and all values in between definitely meet it. 它甚至不需要直接针对k测试大多数值,因为bisect找到满足不同条件的索引的结尾,并且介于两者之间的所有值都一定会满足它。

Rather than building the list manually, I've made this a generator function that can be converted to the L and R values with zip and unpacking: 我不是手动构建list ,而是使它成为一个生成器函数,可以使用zip和解zip将其转换为LR值:

>>> A = [3.5,5,6,12,13] 
>>> k = 1.7
>>> L, R = zip(*fun(A, k))
>>> print(L, R)
(0, 1, 3), (1, 2, 4)

You could do it with list s explicitly: 您可以使用list明确地做到这一点:

def fun(A, k):
    L, R = [], []
    for l, x in enumerate(A):
        newr = range(l+1, bisect(A, x+k, l+1))
        L += [l] * len(newr)
        R.extend(newr)
    return L, R

but I kind of like the generator->zip->unpack approach for letting Python do most of the work. 但是我有点喜欢使用generator-> zip-> unpack方法来让Python完成大部分工作。 Either way, the theoretical cost of O(n log n) is better than O(n * (n - 1) / 2) (roughly O(n ** 2) ). 无论哪种方式, O(n log n)的理论成本都比O(n * (n - 1) / 2) (大约O(n ** 2) )好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找数组中两个数字的总和是否等于 k - Find if sum of two numbers in an array is equal to k 查找长度小于或等于 L 的 n 的所有分区 - Find all partitions of n of length less-than-or-equal to L 找出所有小于 200 万的奇数斐波那契数的总和 - Find the sum of all odd Fibonacci numbers less than 2 million 如何找到 GCD 等于 1 并且这些数字小于 python 中给出的数字 - How to find numbers which GCD equal to 1 and those numbers are less than given in python 找出所有能被 10 整除且小于 n 的正数 - Find all positive numbers divisible by 10 and less than n 我如何找到所有可能的方法,我可以将一个数组安装到 4 个插槽中,并且数组可能有更多/少于 4 个数字? - How do I find all possible ways I can fit an array to 4 slots with the possibility of the array having more/less than 4 numbers? 质数小于或等于n - Prime numbers less than or equal to n 从小于或等于某个 N 的数字列表中最小化或找到理想的子集和 - Minimize or find a n ideal subset-sums from a list of numbers which are less than or equal to some N 查找小于或等于用户使用循环输入的数字的素数。 我怎么做? - Find prime numbers less than or equal to the number the user has entered with loops. How do I do that? 和小于或等于 k 的最长子数组的长度 - Length of longest subarray of sum less than or equal to k
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM