【发布时间】:2015-05-15 20:15:32
【问题描述】:
让我们假设这个任务:
生成大随机数的数组 A。对它们进行排序。然后生成随机数并检查数组A中是否存在这样的数字。重复。如果找到,则返回其在数组 A 中的原始位置(排序前)和数字的值。
示例:排序前的数组A:
+-------+------------------------+
| index | 0 1 2 3 4 5 6 7 8 |
| value | 1 3 9 27 81 17 51 40 7 |
+-------+------------------------+
排序后:
+-------+------------------------+
| index | 0 1 8 2 5 9 3 7 6 |
| value | 1 3 7 9 17 21 27 40 51 |
+-------+------------------------+
数组中是否存在数字 21?是的,在索引 9 上!
我想出了以下解决方案:
def value_exists(needle, haystack):
# finds if needle exists in haystack of tuples and returns it if so
for item in haystack:
if item[1] > needle:
return None
if item[1] == needle:
return item
n = 200000
size = 100000000
# fill array A with random numbers
arrayA = [1]
for i in range(1, n):
arrayA.append(randint(0, size))
arrayA = enumerate(arrayA)
# sort them by values keeping its indexes
arrayA = sorted(arrayA, key=lambda x: x[1])
# search
for i in range(1, n):
value = randint(0, size)
check = value_exists(value, arrayA)
if check:
break
if check:
print(check)
此解决方案有效,但速度极慢。对于设置为100,000,000 的大小,大约需要 30 秒。对于10,000,000,000,我什至无法得到结果(>5 分钟)。
我无法意识到这项任务如此耗时。我知道数字很大,但它们适合 64 位整数。我发现value_exists函数是问题的核心,可以改进吗?
【问题讨论】:
标签: python list sorting python-3.x