zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    Linux显示2015年日历表
    Linux显示系统日期
    Dialogs 对话框
    grid 属性
    VS2010 fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏 嵌入清单
    Perl Tk grid 布局
    Perl Tk pack布局示例
    Perl Tk grid布局管理器
    Perl DBI模块
    输入文本框模型
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12114044.html
Copyright © 2011-2022 走看看