[Swift Weekly Contest 110]LeetCode939. 最小面积矩形 | Minimum Area Rectangle

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

If there isn't any rectangle, return 0.

Example 1:

Input: [[1,1],[1,3],[3,1],[3,3],[2,2]]
Output: 4

Example 2:

Input: [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
Output: 2

Note:

  1. 1 <= points.length <= 500
  2. 0 <= points[i][0] <= 40000
  3. 0 <= points[i][1] <= 40000
  4. All points are distinct.

给定在 xy 平面上的一组点,确定由这些点组成的矩形的最小面积,其中矩形的边平行于 x 轴和 y 轴。

如果没有任何矩形,就返回 0。

示例 1:

输入:[[1,1],[1,3],[3,1],[3,3],[2,2]]
输出:4

示例 2:

输入:[[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
输出:2

提示:

  1. 1 <= points.length <= 500
  2. 0 <= points[i][0] <= 40000
  3. 0 <= points[i][1] <= 40000
  4. 所有的点都是不同的。

2624ms
 1 class Solution {
 2     func minAreaRect(_ points: [[Int]]) -> Int {
 3         var n:Int = points.count
 4         var set:Set<Int64> = Set<Int64>()
 5         for i in 0..<n
 6         {
 7             set.insert(Int64(points[i][0]<<32|points[i][1]))
 8         }
 9         
10         var ret:Int = Int.max
11         for i in 0..<n
12         {
13             for j in (i + 1)..<n
14             {
15                 let S:Int64 = abs(Int64((points[i][0]-points[j][0])*(points[i][1]-points[j][1])))
16                 if S == 0 {continue}
17                 var x:Int64 = Int64(points[i][0]<<32|points[j][1])
18                 if !set.contains(x) {continue}
19                 x = Int64(points[j][0]<<32|points[i][1])
20                 if !set.contains(x) {continue}
21                 ret = min(ret, Int(S))
22             }
23         }
24         if ret == Int.max {return 0}
25         return ret
26     }
27 }

猜你喜欢

转载自www.cnblogs.com/strengthen/p/9942063.html