标签:ash add free img node blog sqrt rmi dia
原题链接在这里:https://leetcode.com/problems/minimum-area-rectangle-ii/
题目:
Given a set of points in the xy-plane, determine the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the x and y axes.
If there isn‘t any rectangle, return 0.
Example 1:
Input: [[1,2],[2,1],[1,0],[0,1]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [1,2],[2,1],[1,0],[0,1], with an area of 2.
Example 2:
Input: [[0,1],[2,1],[1,1],[1,0],[2,0]]
Output: 1.00000
Explanation: The minimum area rectangle occurs at [1,0],[1,1],[2,1],[2,0], with an area of 1.
Example 3:
Input: [[0,3],[1,2],[3,1],[1,3],[2,1]]
Output: 0
Explanation: There is no possible rectangle to form from these points.
Example 4:
Input: [[3,1],[1,1],[0,1],[2,1],[3,3],[3,2],[0,2],[2,3]]
Output: 2.00000
Explanation: The minimum area rectangle occurs at [2,1],[2,3],[3,3],[3,1], with an area of 2.
Note:
1 <= points.length <= 50
0 <= points[i][0] <= 40000
0 <= points[i][1] <= 40000
10^-5
of the actual value will be accepted as correct.题解:
For rectangle, diagonal length are equal and diagonal equally cut each other.
For a pair of nodes, we store distance, and middle x and middle y as key.
If there is antoehr pair of nodes having same distance, middle x and middle y, then these 2 pairs could be used to construct rectangle.
Time Complexity: O(n^2). n = points.length.
Space: O(n^2).
AC java:
1 class Solution { 2 public double minAreaFreeRect(int[][] points) { 3 if(points == null || points.length < 4){ 4 return 0; 5 } 6 7 int n = points.length; 8 HashMap<String, List<int[]>> hm = new HashMap<>(); 9 for(int i = 0; i < n; i++){ 10 for(int j = i + 1; j < n; j++){ 11 double diaDist = dist(points[i], points[j]); 12 double midX = ((double)points[i][0] + (double)points[j][0]) / 2.0; 13 double midY = ((double)points[i][1] + (double)points[j][1]) / 2.0; 14 String key = midX + "," + midY + "," + diaDist; 15 hm.putIfAbsent(key, new ArrayList<>()); 16 hm.get(key).add(new int[]{i, j}); 17 } 18 } 19 20 double res = Double.MAX_VALUE; 21 for(List<int[]> value : hm.values()){ 22 if(value.size() > 1){ 23 for(int i = 0; i < value.size(); i++){ 24 for(int j = i + 1; j < value.size(); j++){ 25 int [] p1 = points[value.get(i)[0]]; 26 int [] p2 = points[value.get(j)[0]]; 27 int [] p3 = points[value.get(j)[1]]; 28 res = Math.min(res, dist(p1, p2) * dist(p1, p3)); 29 } 30 } 31 } 32 } 33 34 return res == Double.MAX_VALUE ? 0 : res; 35 } 36 37 private double dist(int [] p1, int [] p2){ 38 long x = p1[0] - p2[0]; 39 long y = p1[1] - p2[1]; 40 return Math.sqrt(x * x + y * y); 41 } 42 }
LeetCode 963. Minimum Area Rectangle II
标签:ash add free img node blog sqrt rmi dia
原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/12114048.html