algorithm - 找到所有四元组 [a, b, c, d] 其中 a^3 + b^3 = c^3 + d^3 when 1 <= a, b, c or d <= 10000

标签 algorithm complexity-theory

<分区>

寻找算法或一些编码提示以找到解决方案

a^3 + b^3 = c^3 + d^3,其中 a、b、c 和 d 都在 [ 1 .. 10000]

这是一道面试题。

我正在考虑优先级队列至少迭代 ab 值。一些提示会很好,会尝试从那里开始。

最佳答案

使用 HashMap 存储(cube,(a,b)),可以迭代所有可能的整数对,并在找到所需的立方和后输出解决方案已经在 map 上了。

伪代码:

map <- empty hash_map<int,list<pair<int,int>>>
for each a in range(0,10^5):
  for each b in range(a,10^5): //making sure each pair repeats only once
     cube <- a^3 + b^3
     if map.containsKey(cube):
         for each element e in map.get(cube):
            output e.first(), e.last(), a, b //one solution            
     else:
         map.put(cube,new list<pair<int,int>>)
     //for both cases, add the just found pair to the relevant list
     map.get(cube).add(cube,new pair(a,b))  

这个解决方案平均是 O(n^2) 空间(1) 和 O(n^2 + OUTPUT) 时间,其中 OUTPUT 是输出的大小。

编辑:

所需空间实际上是O(n^2 logn),其中n是范围(10^5),因为要表示10^5 整数你需要 ceil(log_2(10^15)) = 50 位。因此,您实际上需要大约 500,000,000,000 位(+ map 和列表的开销),即 ~58.2 GB(+ 开销)。

因为对于大多数机器来说,它有点太多了 - 你可能想考虑将数据存储在磁盘上,或者如果你有 64 位机器 - 只需存储到“内存”中并让操作系统和 virtual memory系统会尽可能地做到这一点。


(1) 正如编辑所阐明的那样,它实际上是 O(n^2log(n)) 空间,但是如果我们将每个整数存储作为 O(1)(通常是这种情况)我们得到 O(n^2) 空间。显然,同样的原则也适用于时间复杂度。

关于algorithm - 找到所有四元组 [a, b, c, d] 其中 a^3 + b^3 = c^3 + d^3 when 1 <= a, b, c or d <= 10000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14454133/

相关文章:

algorithm - 简单算法分析

algorithm - 为 Somp 操作设计数据结构

algorithm - 使用 2 组坐标对真阳性、假阳性和假阴性进行分类

php - 尽管满足条件,但如果在条件语句中调用 return,则函数返回 null。返回条件之外的期望值

c++ - std::lower_bound 与 std::set 的时间复杂度是多少?

f>>g & f>g的算法复杂度题

java - 数组子序列的最大可能平均值——需要有效的解决方案

algorithm - 在 BST 中找到 k 个后继者的时间复杂度

python - cProfile.run 函数调用与复杂性

algorithm - 给定一个整数数组 A1, A2, ..., An