Minimum Area Rectangle II

update Dec 27, 22:35 2018

LeetCodearrow-up-right

Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the x and y axes.

If there isn't any rectangle, return 0.

Example 1:

Example 2:

Example 3:

Example 4:

Note:

  1. 1 <= points.length <= 50

  2. 0 <= points[i][0] <= 40000

  3. 0 <= points[i][1] <= 40000

  4. All points are distinct.

  5. Answers within 10^-5 of the actual value will be accepted as correct.

Basic Idea:

  • 对角线长度相等且互相平分

    我们可以利用矩形的性质:对角线平分且长度相等的四边形是矩形。于是我们可以先用 O(n^2) 的时间枚举所有的两点连线,以他们的长度和中点坐标为key存入map。然后对map中的每一组互相平分长度相等的连线,两重for loop计算每个矩形的面积。

    时间复杂度是 O(n^2),因为所有连线最多 n(n-1)/2,而我们知道不同组的长度相同且平分的对角线之间不会出现这种关系,所以amortized来说,共有最多 O(n^2) 个矩形,而后面的两重for loop实际上是检查了所有的矩形,所以总时间复杂度仍然是 O(n^2)

  • O(n^3) solution

    列出这个解法主要是为了复习一些向量的操作手法。我们可以 O(n^3) 时间枚举所有的三个点的组合,利用向量的性质判断它们能否组成矩形的互相垂直的两条边,然后利用向量的性质求出第四个点的坐标,判断其是否存在。然后就可以计算面积了。