标签:points point nim find == integer minimum determine time
原题链接在这里: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 <= points.length <= 500
0 <= points[i][0] <= 40000
0 <= points[i][1] <= 40000
题解:
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.
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 }
LeetCode 939. Minimum Area Rectangle
标签:points point nim find == integer minimum determine time
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12114044.html