【问题标题】:Given a number X , find two elements in two sorted arrays such A[i]+B[j] = X in O(n+m)给定一个数字 X ,在两个排序数组中找到两个元素,例如 A[i]+B[j] = X in O(n+m)
【发布时间】:2023-03-24 14:27:02
【问题描述】:

鉴于以下问题,我不胜感激任何更正,因为我没有解决方案 对于当前问题(取自我教授的一项考试!!!):

备注:这不是功课!

问题:

给定两个排序数组A(长度为n)和B(长度为m),其中每个

元素(在两个数组中)是一个实数,一个数字X(也是一个实数),

我们想知道a ∈ Ab ∈ B是否存在,如:

a + b = X,在O(n+m)运行时间。

解决方案:

首先,我们从两个数组的末尾开始检查,因为我们不需要大于X 的数字:

  • i = n
  • k = m

  • 而 A[i] > X , i = i -1

  • 当 B[k] > X , k = k -1

定义 j = 0 。 现在从A 中的当前iB 中的j 开始运行:

  • while i > 0 , j < k
  • if A[i]+B[j] == X ,然后返回两个单元格
  • 否则j = j+1 , i = i -1

最后我们要么拥有这两个元素,要么我们会合二为一 或两个数组,这意味着确实不存在像a + b = X 这样的两个元素。

任何意见将不胜感激

谢谢

【问题讨论】:

  • 也许你可以用伪代码写下你的整个算法。英语和伪代码之间的混合让我感到困惑。
  • 请注意,您可以省略预处理。您可以将递减 i 留给主循环,对于 j 使用合适的循环条件(j ≤ m 和 B[j] ≤ X)。在数组中允许负数的情况下,您不应该进行任何此类优化。

标签: arrays algorithm sorting big-o


【解决方案1】:

您不应同时调整ij。如果总和太大,你应该减少i。如果太小,增加j

【讨论】:

  • 值得注意的事情。但是,这是否仍然导致 O(n*m) 解决方案?
  • @BlackVegetable: O(n+m) 是,是的,确实如此。在每一步中,您都在一个数组中移动另一个数组,因此结合起来,您移动的次数不能超过两个数组长度的总和。
【解决方案2】:

这个问题是以下问题的特例: Find number in sorted matrix (Rows n Columns) in O(log n)

考虑一个用C[i,j] = A[i] + B[j] 填充的矩阵,然后从其中一个角开始,如果总和太大,则减少i,如果太小,则增加j。 当然,您不必在程序中创建和/或填充此矩阵C,只需假设您知道此矩阵的任何元素:它是A[i] + B[j],您可以随时立即计算它。生成的算法是O(m+n)

【讨论】:

  • 我放了一个更简洁的问题链接:)
【解决方案3】:

我有同样的家庭作业问题。 在上网查之前我已经练过了。 这是我的解决方案(Python),希望有大佬看到并帮助我改进它

# 1.3. Given two sorted arrays a and b and number S. Find two elements such that sum a[i] + b[j] = S.Time O(n).

def find_elem_sum(alist, blist, S): # O(n)

if alist is None or alist == [] or blist is None or blist == []:
    return None

# find the numbers which are less than S in the lists
#
#
# pretend it is done

a_length = len(alist)
b_length = len(blist)
a_index, b_index = 0, 0
count = 0
while alist and a_index < a_length and b_index < b_length:
    count += 1
    if alist[a_index] + blist[b_index] < S:
        if a_index < a_length - 1:
            a_index += 1
        if a_index == a_length - 1:
            b_index += 1;
        continue
    elif alist[a_index] + blist[b_index] > S:
        alist = alist[:a_index]
        a_length = len(alist)
        a_index = a_length - 1
    elif alist[a_index] + blist[b_index] == S:
        return [a_index, b_index, count]

return None

【讨论】:

    猜你喜欢
    • 2012-04-16
    • 2021-11-01
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-06
    相关资源
    最近更新 更多