[英]how find the shortest distance between two numbers in a random list without sorting the list. my code is given below , i need another FAST way
import random
L = [random.randrange(1, 100**7) for i in range(100*100)]
#it creates a random list
for x in L:
min = L[0]
for y in L:
if x != y and abs(x-y) < min:
min = abs(x-y)
**#it basically cheeks every element with every one and update the min value id new one is found**
print(min)
any faster way doing so without sorting?没有排序的更快的方法吗? someone suggested it can be done using a hashing table but I cant relate to it so pls help me with the logic and connection of this question with hashing table
有人建议它可以使用哈希表来完成,但我无法与之相关,所以请帮助我解决这个问题与哈希表的逻辑和联系
The numbers can be stored in nested lists according with its binary (or whatever) representation.数字可以根据其二进制(或其他)表示存储在嵌套列表中。 We use a fix digits number (for this example 3).
我们使用固定数字(对于本例 3)。 For example 2 will be represented as
010
例如 2 将表示为
010
Then we put an element in然后我们放入一个元素
numbers[0][1][0]
The tree with just the number 2 would be:只有数字 2 的树将是:
[
[None, [True, None]], None
]
If we add number 3 (011):如果我们添加数字 3 (011):
[
[None, [True, True]], None
]
add number 1 (001):添加数字 1 (001):
[
[[None, True], [True, True]], None
]
All the lists has 2 elements and are created as needed.所有列表都有 2 个元素,并根据需要创建。 Unused elelements are set to 'None'
未使用的元素被设置为“无”
We actually dont need to put the number because all the information is in the indices.我们实际上不需要输入数字,因为所有信息都在索引中。 So we put just
True
to say that the number 2 is in the tree.所以我们只用
True
表示数字 2 在树中。
Now to find the closer number in the tree to some other number just do a binary search.现在要在树中找到与其他数字更接近的数字,只需进行二分搜索即可。
Now compare the minimal distance with the stored minimal distance , update the stored minimal distance if needed and store the new number in the tree.现在将最小距离与存储的最小距离进行比较,如果需要更新存储的最小距离并将新数字存储在树中。
I think this O(N * logN).我认为这是 O(N * logN)。 The log comes from the binary storage and search.
日志来自二进制存储和搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.