Given a grid where each entry is only 0 or 1, find the number of corner rectangles.

corner rectangle is 4 distinct 1s on the grid that form an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1s used must be distinct.

Example 1:

  1. Input: grid =
  2. [[1, 0, 0, 1, 0],
  3. [0, 0, 1, 0, 1],
  4. [0, 0, 0, 1, 0],
  5. [1, 0, 1, 0, 1]]
  6. Output: 1
  7. Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].

Example 2:

  1. Input: grid =
  2. [[1, 1, 1],
  3. [1, 1, 1],
  4. [1, 1, 1]]
  5. Output: 9
  6. Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.

Example 3:

  1. Input: grid =
  2. [[1, 1, 1, 1]]
  3. Output: 0
  4. Explanation: Rectangles must have four distinct corners. 

Note:

  1. The number of rows and columns of grid will each be in the range [1, 200].
  2. Each grid[i][j] will be either 0 or 1.
  3. The number of 1s in the grid will be at most 6000.

给了一个由0和1组成的二维数组,定义了一种边角矩形,其四个顶点均为1,求这个二维数组中有多少个不同的边角矩形。

不能一个一个的数,先固定2行,求每列与这2行相交是不是都是1 ,计算这样的列数,然后用公式:n*(n-1)/2,得出能组成的边角矩形,累加到结果中。

解法:枚举,枚举任意两行r1和r2,看这两行中存在多少列,满足在该列中第r1行和第r2行中对应的元素都是1。假设有counter列满足条件,那么这两行可以构成的的recangles的数量就是counter * (counter - 1) / 2。最后返回所有rectangles的数量即可。如果假设grid一共有m行n列,时间复杂度就是O(m^2n),空间复杂度是O(1)。如果m远大于n的时候,还可以将时间复杂度优化到O(mn^2)。

Java:

  1. class Solution {
  2. public int countCornerRectangles(int[][] grid) {
  3. int m = grid.length, n = grid[0].length;
  4. int ans = 0;
  5. for (int x = 0; x < m; x++) {
  6. for (int y = x + 1; y < m; y++) {
  7. int cnt = 0;
  8. for (int z = 0; z < n; z++) {
  9. if (grid[x][z] == 1 && grid[y][z] == 1) {
  10. cnt++;
  11. }
  12. }
  13. ans += cnt * (cnt - 1) / 2;
  14. }
  15. }
  16. return ans;
  17. }
  18. }  

Python:

  1. def countCornerRectangles(self, grid):
  2. """
  3. :type grid: List[List[int]]
  4. :rtype: int
  5. """
  6. n = len(grid)
  7. m = len(grid[0])
  8. res = 0
  9. for i in xrange(n):
  10. for j in xrange(i + 1, n):
  11. np = 0
  12. for k in xrange(m):
  13. if grid[i][k] and grid[j][k]:
  14. np += 1
  15.  
  16. res += np * (np - 1) / 2
  17. return res 

Python:

  1. # Time: O(n * m^2), n is the number of rows with 1s, m is the number of cols with 1s
  2. # Space: O(n * m)
  3. class Solution(object):
  4. def countCornerRectangles(self, grid):
  5. """
  6. :type grid: List[List[int]]
  7. :rtype: int
  8. """
  9. rows = [[c for c, val in enumerate(row) if val]
  10. for row in grid]
  11. result = 0
  12. for i in xrange(len(rows)):
  13. lookup = set(rows[i])
  14. for j in xrange(i):
  15. count = sum(1 for c in rows[j] if c in lookup)
  16. result += count*(count-1)/2
  17. return result

C++: 暴力,不好

  1. class Solution {
  2. public:
  3. int countCornerRectangles(vector<vector<int>>& grid) {
  4. int m = grid.size(), n = grid[0].size(), res = 0;
  5. for (int i = 0; i < m; ++i) {
  6. for (int j = 0; j < n; ++j) {
  7. if (grid[i][j] == 0) continue;
  8. for (int h = 1; h < m - i; ++h) {
  9. if (grid[i + h][j] == 0) continue;
  10. for (int w = 1; w < n - j; ++w) {
  11. if (grid[i][j + w] == 1 && grid[i + h][j + w] == 1) ++res;
  12. }
  13. }
  14. }
  15. }
  16. return res;
  17. }
  18. };  

C++:

  1. // Time: O(m^2 * n), m is the number of rows with 1s, n is the number of cols with 1s
  2. // Space: O(m * n)
  3. class Solution {
  4. public:
  5. int countCornerRectangles(vector<vector<int>>& grid) {
  6. vector<vector<int>> rows;
  7. for (int i = 0; i < grid.size(); ++i) {
  8. vector<int> row;
  9. for (int j = 0; j < grid[i].size(); ++j) {
  10. if (grid[i][j]) {
  11. row.emplace_back(j);
  12. }
  13. }
  14. if (!row.empty()) {
  15. rows.emplace_back(move(row));
  16. }
  17. }
  18. int result = 0;
  19. for (int i = 0; i < rows.size(); ++i) {
  20. unordered_set<int> lookup(rows[i].begin(), rows[i].end());
  21. for (int j = 0; j < i; ++j) {
  22. int count = 0;
  23. for (const auto& c : rows[j]) {
  24. count += lookup.count(c);
  25. }
  26. result += count * (count - 1) / 2;
  27. }
  28. }
  29. return result;
  30. }
  31. };

C++:

  1. class Solution {
  2. public:
  3. int countCornerRectangles(vector<vector<int>>& grid) {
  4. int ans = 0;
  5. for (int r1 = 0; r1 + 1 < grid.size(); ++r1) {
  6. for (int r2 = r1 + 1; r2 < grid.size(); ++r2) {
  7. int counter = 0;
  8. for (int c = 0; c < grid[0].size(); ++c) {
  9. if (grid[r1][c] == 1 && grid[r2][c] == 1) {
  10. ++counter;
  11. }
  12. }
  13. ans += counter * (counter - 1) / 2;
  14. }
  15. }
  16. return ans;
  17. }
  18. };

  

  

  

All LeetCode Questions List 题目汇总

[LeetCode] 750. Number Of Corner Rectangles 边角矩形的数量的更多相关文章

  1. [LeetCode] Number Of Corner Rectangles 边角矩形的数量

    Given a grid where each entry is only 0 or 1, find the number of corner rectangles. A corner rectang ...

  2. leetcode 750. Number Of Corner Rectangles

    Given a grid where each entry is only 0 or 1, find the number of corner rectangles. A corner rectang ...

  3. 750. Number Of Corner Rectangles四周是点的矩形个数

    [抄题]: Given a grid where each entry is only 0 or 1, find the number of corner rectangles. A corner r ...

  4. 【LeetCode】750. Number Of Corner Rectangles 解题报告 (C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历 日期 题目地址:https://leetcode ...

  5. [LeetCode] Minimum Number of Arrows to Burst Balloons 最少数量的箭引爆气球

    There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided ...

  6. C#版 - Leetcode 191. Number of 1 Bits-题解

    版权声明: 本文为博主Bravo Yeung(知乎UserName同名)的原创文章,欲转载请先私信获博主允许,转载时请附上网址 http://blog.csdn.net/lzuacm. C#版 - L ...

  7. [leetcode]200. Number of Islands岛屿个数

    Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surro ...

  8. [leetcode]694. Number of Distinct Islands你究竟有几个异小岛?

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...

  9. [LeetCode] 711. Number of Distinct Islands II_hard tag: DFS

    Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) conn ...

随机推荐

  1. Kotlin中Range与异常体系剖析

    好用的集合扩展方法: 下面来看一下对于集合中好用的一些扩展方法,直接上代码: 如果我们想取出集合中的第一个值和最后一个值,用Java方式是get(0)和get(size-1),但是在Kotlin中提供 ...

  2. Xenia and Weights(Codeforces Round #197 (Div. 2)+DP)

    题目链接 传送门 思路 \(dp[i][j][k]\)表示第\(i\)次操作放\(j\)后与另一堆的重量差为\(k\)是否存在. 代码实现如下 #include <set> #includ ...

  3. 关于mysql数据库utf-8问题

    1.bug的出现 我们正常使用utf-8类型来给我们的字段的字符编码,对于正常的都没有问题,例如姓名呀,性别年龄等,但是会遇到一个问题就是如果存储表情emoji则无法存入utf-8编码的字段 2.my ...

  4. Json在序列化注意问题

    Java中的Json序列化,不容忽视的getter 问题重现 public class AjaxJson { private boolean success; private String msg; ...

  5. Map集合迭代的两种方法

    import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; pub ...

  6. Go语言 - 指针 | new | make

    区别于C/C++中的指针,Go语言中的指针不能进行偏移和运算,是安全指针. 要搞明白Go语言中的指针需要先知道3个概念:指针地址.指针类型和指针取值. 概念 任何程序数据载入内存后,在内存都有他们的地 ...

  7. jsp之大文件分段上传、断点续传

    1,项目调研 因为需要研究下断点上传的问题.找了很久终于找到一个比较好的项目. 在GoogleCode上面,代码弄下来超级不方便,还是配置hosts才好,把代码重新上传到了github上面. http ...

  8. 【JZOJ6222】【20190617】可爱

    题目 给定一个长度为\(n\)的串,定义两个串匹配当且仅当两个串长度相同并且不同字符至多一个 对于每一个长度为\(m\)的子串输出和它匹配的子串个数 $1 \le n \le 10^5  ,  m \ ...

  9. vue使用axios发送请求,都会发送两次请求

    vue 使用axios,每次的请求都会发送两次,第一次的请求头为options CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sha ...

  10. 启动服务器 SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener

    意思是spring.jar这个包在发布的时候没有被放入war.如果是maven管理的项目,可以看看这个项目的部署参数里有没有加入所有maven的包. 右键项目->Properties->D ...