原题链接在这里:
题目:
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
All points are distinct.
Answers within 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:
- class Solution {
- public double minAreaFreeRect(int[][] points) {
- if(points == null || points.length <4){
- return 0;
- }
- int n = points.length;
- HashMap<String, List<int[]>> hm = new HashMap<>();
- for(int i = 0; i <n; i++){
- for(int j = i + 1; j < n; j++){
- double diaDist = dist(points[i], points[j]);
- double midX = ((double)points[i][0] + (double)points[j][0]) / 2.0;
- double midY = ((double)points[i][1] + (double)points[j][1]) / 2.0;
- String key = midX + "," + midY + "," + diaDist;
- hm.putIfAbsent(key, new ArrayList<>());
- hm.get(key).add(new int[]{i, j});
- }
- }
- double res = Double.MAX_VALUE;
- for(List<int[]> value : hm.values()){
- if(value.size()> 1){
- for(int i = 0; i < value.size(); i++){
- for(int j = i + 1; j < value.size(); j++){
- int [] p1 = points[value.get(i)[0]];
- int [] p2 = points[value.get(j)[0]];
- int [] p3 = points[value.get(j)[1]];
- res = Math.min(res, dist(p1, p2) * dist(p1, p3));
- }
- }
- }
- }
- return res == Double.MAX_VALUE ? 0 : res;
- }
- private double dist(int [] p1, int [] p2){
- long x = p1[0] - p2[0];
- long y = p1[1] - p2[1];
- return Math.sqrt(x * x + y * y);
- }
- }
类似 Minimum Area Rectangle.
来源: http://www.bubuko.com/infodetail-3355375.html