1. 程式人生 > >[Swift Weekly Contest 110]LeetCode939. 最小面積矩形 | Minimum Area Rectangle

[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 }