LeetCode 939. Minimum Area Rectangle (最小面积矩形)
题目标签:HashMap
题目给了我们一组 xy 上的点坐标,让我们找出 能组成矩形里最小面积的那个。
首先遍历所有的点,把x 坐标当作key 存入map, 把重复的y坐标 组成set,当作value 存入map。
然后遍历所有的点,找出 对角的两个点, 再去map里确认是否存在剩下的两个对角点,计算面积,一直保留最小的那个面积。
Java Solution:
Runtime: 214 ms, faster than 78.80%
Memory Usage: 61.5 MB, less than 5.97%
完成日期:03/27/2019
关键点:找对角2个点,方便判断和操作。
class Solution { public int minAreaRect(int[][] points) { Map<Integer, Set<Integer>> map = new HashMap<>(); int minArea = Integer.MAX_VALUE; // save each point into map by key as x, value as multiple y for(int[] point : points) { if(!map.containsKey(point[0])) map.put(point[0], new HashSet<>()); map.get(point[0]).add(point[1]); } // find 2 diagonal points and then find the other 2 diagonal points to calculate the area for(int[] point1 : points) { for(int[] point2: points) { if(point1[0] == point2[0] || point1[1] == point2[1]) // if point1 and point2 are not diagonal continue; if(map.get(point1[0]).contains(point2[1]) && map.get(point2[0]).contains(point1[1])) // if find the other 2 diagonal points minArea = Math.min(minArea, Math.abs(point2[0] - point1[0]) * Math.abs(point2[1] - point1[1])); } } return minArea == Integer.MAX_VALUE ? 0 : minArea; } }
参考资料:https://leetcode.com/problems/minimum-area-rectangle/discuss/?currentPage=1&orderBy=recent_activity&query=
LeetCode 题目列表 - LeetCode Questions List
题目来源:https://leetcode.com/