给定一个包含N个点和一个参考点P的数组 arr[] ,任务是根据它们与给定点P的距离对这些点进行排序。
例子:
Input: arr[] = {{5, 0}, {4, 0}, {3, 0}, {2, 0}, {1, 0}}, P = (0, 0)
Output: (1, 0) (2, 0) (3, 0) (4, 0) (5, 0)
Explanation:
Distance between (0, 0) and (1, 0) = 1
Distance between (0, 0) and (2, 0) = 2
Distance between (0, 0) and (3, 0) = 3
Distance between (0, 0) and (4, 0) = 4
Distance between (0, 0) and (5, 0) = 5
Hence, the sorted array of points will be: {(1, 0) (2, 0) (3, 0) (4, 0) (5, 0)}
Input: arr[] = {{5, 0}, {0, 4}, {0, 3}, {2, 0}, {1, 0}}, P = (0, 0)
Output: (1, 0) (2, 0) (0, 3) (0, 4) (5, 0)
Explanation:
Distance between (0, 0) and (1, 0) = 1
Distance between (0, 0) and (2, 0) = 2
Distance between (0, 0) and (0, 3) = 3
Distance between (0, 0) and (0, 4) = 4
Distance between (0, 0) and (5, 0) = 5
Hence, the sorted array of points will be: {(1, 0) (2, 0) (0, 3) (0, 4) (5, 0)}
方法:思想是将距离给定点P的每个元素成对存储,然后根据存储的距离对向量的所有元素进行排序。
- 对于每个给定的点:
- 求该点到参考点 P 的距离公式如下:
距离 =
- 在数组中追加距离
- 对距离数组进行排序并根据排序后的距离打印点。
- 时间复杂度:与上述方法一样,对长度为 N 的数组进行排序,在最坏的情况下需要 O(N*logN) 时间。因此,时间复杂度将为O(N*log N) 。
- 辅助空间复杂度:与上述方法一样,有额外的空间用于将距离和点存储为成对。因此,辅助空间复杂度将为O(N) 。
Javascript