📌  相关文章
📜  找到任意一对之间曼哈顿距离相等的 4 个点(1)

📅  最后修改于: 2023-12-03 15:10:05.776000             🧑  作者: Mango

查找任意一对之间曼哈顿距离相等的 4 个点

假设有一个平面上的点集,要找到任意一对之间曼哈顿距离相等的4个点。

思路
  1. 将所有点按照x坐标排序;
  2. 利用哈希表存储所有点的y坐标;
  3. 枚举每一对点,计算它们之间的曼哈顿距离,查找是否有相同距离的点对。
代码实现
def find_4_points(points):
    sorted_points = sorted(points, key=lambda p: p[0])
    points_dict = {}
    for point in points:
        if point[1] not in points_dict:
            points_dict[point[1]] = []
        points_dict[point[1]].append(point)

    for i in range(len(sorted_points)):
        for j in range(i+1, len(sorted_points)):
            x1, y1 = sorted_points[i]
            x2, y2 = sorted_points[j]
            distance = abs(x1 - x2) + abs(y1 - y2)
            if distance % 2 == 1:  # 如果曼哈顿距离为奇数,则跳过
                continue
            mid_x = (x1 + x2) / 2
            mid_y = (y1 + y2) / 2
            if mid_y not in points_dict:
                continue
            for k in range(len(points_dict[mid_y])):
                if points_dict[mid_y][k] == (mid_x, mid_y):
                    continue
                x3, y3 = points_dict[mid_y][k]
                distance2 = abs(x1 - x3) + abs(y1 - y3)
                if distance == distance2:
                    for l in range(k+1, len(points_dict[mid_y])):
                        if points_dict[mid_y][l] == (mid_x, mid_y):
                            continue
                        x4, y4 = points_dict[mid_y][l]
                        distance3 = abs(x1 - x4) + abs(y1 - y4)
                        if distance == distance3:
                            return sorted([(x1, y1), (x2, y2), (x3, y3), (x4, y4)])
    return None
测试样例
points = [(1, 1), (1, 5), (3, 3), (5, 5), (7, 3), (9, 1)]
assert find_4_points(points) == [(1, 1), (1, 5), (5, 5), (5, 1)]

points = [(1, 1), (1, 5), (4, 4), (5, 5), (7, 3), (9, 1)]
assert find_4_points(points) == [(1, 1), (1, 5), (5, 5), (5, 1)]

points = [(1, 1), (1, 2), (1, 3), (1, 4)]
assert find_4_points(points) == [(1, 1), (1, 4), (1, 2), (1, 3)]

points = [(1, 1), (2, 2), (3, 3), (4, 4)]
assert find_4_points(points) is None

参考资料:

  1. leetcode官方题解
  2. 极客时间算法面试题第16讲