我曾经在一次工作面试中遇到了这个问题,但我没有通过这个测试。出于对公司的尊重,我不会透露具体问题。
假设你在一个 A x B 的公园里有 N 个人。如果一个人周围50英尺内没有其他人,他就可以享受自己的私人空间。否则,他的私人空间就会被侵犯。给定一组 (x, y) 坐标,有多少人的空间会被侵犯?
例如,在 Python 中给出以下列表:
people = [(0,0), (1,1), (1000, 1000)]
我们将找到2个人的空间被侵犯:1, 2。
我们不需要找到所有人的组合,只需要找到唯一的人数。
不能使用暴力方法解决该问题。换句话说,不能使用简单的数组嵌套。
我已经花费几周时间一直在解决这个问题,虽然我已经得到了比n^2更快的解决方案,但还没有想出一个可扩展的解决方案。
我认为解决这个问题的唯一正确方式是使用 Fortune 算法?
以下是我的 Python 代码(未使用 Fortune 算法):
import math
import random
random.seed(1) # Setting random number generator seed for repeatability
TEST = True
NUM_PEOPLE = 10000
PARK_SIZE = 128000 # Meters.
CONFLICT_RADIUS = 500 # Meters.
def _get_distance(x1, y1, x2, y2):
"""
require: x1, y1, x2, y2: all integers
return: a distance as a float
"""
distance = math.sqrt(math.pow((x1 - x2), 2) + math.pow((y1 - y2),2))
return distance
def check_real_distance(people1, people2, conflict_radius):
"""
determine if two people are too close
"""
if people2[1] - people1[1] > conflict_radius:
return False
d = _get_distance(people1[0], people1[1], people2[0], people2[1])
if d >= conflict_radius:
return False
return True
def check_for_conflicts(peoples, conflict_radius):
# sort people
def sort_func1(the_tuple):
return the_tuple[0]
_peoples = []
index = 0
for people in peoples:
_peoples.append((people[0], people[1], index))
index += 1
peoples = _peoples
peoples = sorted(peoples, key = sort_func1)
conflicts_dict = {}
i = 0
# use a type of sweep strategy
while i < len(peoples) - 1:
x_len = peoples[i + 1][0] - peoples[i][0]
conflict = False
conflicts_list =[peoples[i]]
j = i + 1
while x_len <= conflict_radius and j < len(peoples):
x_len = peoples[j][0] - peoples[i][0]
conflict = check_real_distance(peoples[i], peoples[j], conflict_radius)
if conflict:
people1 = peoples[i][2]
people2 = peoples[j][2]
conflicts_dict[people1] = True
conflicts_dict[people2] = True
j += 1
i += 1
return len(conflicts_dict.keys())
def gen_coord():
return int(random.random() * PARK_SIZE)
if __name__ == '__main__':
people_positions = [[gen_coord(), gen_coord()] for i in range(NUM_PEOPLE)]
conflicts = check_for_conflicts(people_positions, CONFLICT_RADIUS)
print("people in conflict: {}".format(conflicts))
sqrt(dx*dx + dy*dy) >= 50
,不如检查dx*dx + dy*dy >= 2500
。后者可以使用整数运算来完成,并给出精确结果(没有舍入误差的可能性)。 - user3386109