LeetCode 939. Minimum Area Rectangle

Posted Dylan_Java_NYC

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 939. Minimum Area Rectangle相关的知识,希望对你有一定的参考价值。

原题链接在这里:https://leetcode.com/problems/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.

题解:

Use a HashMap to maintain all y of the same x.

Then try to find the diagonal nodes, get one node from x and one node from y, if x[0] == y[0] || x[1] == y[1], skip, they can\'t be diagonal nodes.

Else if in x[0] HashMap entry contains y[1] and in y[0] HashMap entry contains x[1], then x and y could diagonal nodes. Use it to update rectangle size.

Note: check res == Integer.MAX_VALUE before return.

Time Complexity: O(n ^ 2). n = points.length.

Space: O(n).

AC Java:

 1 class Solution {
 2     public int minAreaRect(int[][] points) {
 3         if(points == null || points.length < 4){
 4             return 0;
 5         }
 6         
 7         HashMap<Integer, Set<Integer>> hm = new HashMap<>();
 8         for(int [] p : points){
 9             hm.putIfAbsent(p[0], new HashSet<>());
10             hm.get(p[0]).add(p[1]);
11         }
12         
13         int res = Integer.MAX_VALUE;
14         for(int [] p1 : points){
15             for(int [] p2 : points){
16                 if(p1[0] == p2[0] || p1[1] == p2[1]){
17                     continue;
18                 }
19                 
20                 if(hm.get(p1[0]).contains(p2[1]) && hm.get(p2[0]).contains(p1[1])){
21                     res = Math.min(res, Math.abs(p2[0] - p1[0]) * Math.abs(p2[1] - p1[1]));
22                 }
23             }
24         }
25         
26         return res == Integer.MAX_VALUE ? 0 : res;
27     }
28 }

跟上Minimum Area Rectangle II.

以上是关于LeetCode 939. Minimum Area Rectangle的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces 939A题水题

LeetCode939 最小面积矩形

Leetcode.939 最小面积矩形

LeetCode Minimum Height Trees

leetcode:Minimum Subarray

leetcode@ [310] Minimum Height Trees