> 文章列表 > Leetcode.939 最小面积矩形

Leetcode.939 最小面积矩形

Leetcode.939 最小面积矩形

题目链接

Leetcode.939 最小面积矩形 Rating : 1752

题目描述

给定在 xy平面上的一组点,确定由这些点组成的矩形的最小面积,其中矩形的边平行于 x 轴和 y 轴。

如果没有任何矩形,就返回 0

示例 1:

输入:[[1,1],[1,3],[3,1],[3,3],[2,2]]
输出:4

示例 2:

输入:[[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]
输出:2

提示:

  • 1<=points.length<=5001 <= points.length <= 5001<=points.length<=500
  • 0<=points[i][0]<=400000 <= points[i][0] <= 400000<=points[i][0]<=40000
  • 0<=points[i][1]<=400000 <= points[i][1] <= 400000<=points[i][1]<=40000
  • 所有的点都是不同的

解法:哈希表 + 枚举

对于每一个点 (x,y),我们都可以存入到一个哈希表 uset中。

因为每一个点的最大值是 40000。为了方便,我们可以存入 x * 40001 + y这样的一个数到 uset中。将两个点映射成一个数。

接下来枚举矩形的 左上角顶点(x1 , y1)右下角顶点(x2 , y2)。 再判断另外两个顶点在不在集合中,同时在的话,就可以构成一个矩形。

Leetcode.939 最小面积矩形

时间复杂度:O(n2)O(n^2)O(n2)

C++代码:

class Solution {
public:int minAreaRect(vector<vector<int>>& points) {unordered_set<int> uset;for(auto &p:points){uset.insert(p[0] * 40001 + p[1]);}int n = points.size();int s = 1e9;for(int i = 0;i < n;i++){int x1 = points[i][0] , y1 = points[i][1];for(int j = i + 1;j < n;j++){int x2 = points[j][0] , y2 = points[j][1];if(x1 == x2 || y1 == y2) continue;if(uset.count(x1 * 40001 + y2) && uset.count(x2 * 40001 + y1)){int a = abs(x1 - x2);int b = abs(y1 - y2);s = min(s,a * b);}}}return s == 1e9 ? 0 : s;}
};