LWC 63: 750. Number Of Corner Rectangles
来源:互联网 发布:淘宝家具排行 编辑:程序博客网 时间:2024/06/01 10:42
LWC 63: 750. Number Of Corner Rectangles
传送门:750. Number Of Corner Rectangles
Problem:
Given a grid where each entry is only 0 or 1, find the number of corner rectangles.
A 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:
Input: grid =
[[1, 0, 0, 1, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 0],
[1, 0, 1, 0, 1]]
Output: 1
Explanation: There is only one corner rectangle, with corners grid1[2], grid1[4], grid[3][2], grid[3][4].
Example 2:
Input: grid =
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
Output: 9
Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.
Example 3:
Input: grid =
[[1, 1, 1, 1]]
Output: 0
Explanation: Rectangles must have four distinct corners.
Note:
- The number of rows and columns of grid will each be in the range [1, 200].
- Each grid[i][j] will be either 0 or 1.
- The number of 1s in the grid will be at most 6000.
思路:
暴力搜索,实际上如果矩形的纵向边被确定了,只要有两条以上自然能构成矩形,所以只需要遍历不同的两行,找能够构成纵向边的个数,再组合一波即可。
Java版本:
public int countCornerRectangles(int[][] grid) { int n = grid.length; int m = grid[0].length; int ret = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int np = 0; for (int k = 0; k < m; ++k) { if (grid[i][k] == 1 && grid[j][k] == 1) { np ++; } } ret += np * (np - 1) / 2; } } return ret; }
Python版本:
def countCornerRectangles(self, grid): """ :type grid: List[List[int]] :rtype: int """ n = len(grid) m = len(grid[0]) res = 0 for i in xrange(n): for j in xrange(i + 1, n): np = 0 for k in xrange(m): if grid[i][k] and grid[j][k]: np += 1 res += np * (np - 1) / 2 return res
- LWC 63: 750. Number Of Corner Rectangles
- 750. Number Of Corner Rectangles
- LWC 53:694. Number of Distinct Islands
- LWC 58:726. Number of Atoms
- LeetCode | 750. Number Of Corner Rectangles12_17 | 二维数组技巧题
- LWC 49:673. Number of Longest Increasing Subsequence
- LWC 64: 747. Largest Number Greater Than Twice of Others
- LWC 53:695. Max Area of Island
- LWC 54:697. Degree of an Array
- No. 27 - Area of Rectangles
- LWC 63: 749. Contain Virus
- LWC 53:693. Binary Number with Alternating Bits
- Rectangles
- Rectangles
- Rectangles
- Rectangles
- Rectangles
- LWC 52:689. Maximum Sum of 3 Non-Overlapping Subarrays
- 算法基础【3】差分与前缀和
- leetcode 609. Find Duplicate File in System C++stringstream的一个很好地示范
- 使用canvas元素绘制指针式动画时钟
- linux下安装7z命令及7z命令的使用
- nginx关于域名解析的源码分析
- LWC 63: 750. Number Of Corner Rectangles
- java排序算法
- 【聚类分析】Kmeans算法理解及R语言实现
- 安装apache 2.4.29
- date('Y-m-d H:i:s',time()) 与 date('Y-m-d h:i:s',time())区别是什么
- 数据结构
- IDEA控制台乱码解决
- 2017年浙江工业大学大学生程序设计迎新赛预赛 D简单的数据结构【纯 stl -> List 的应用】
- iOS 监听耳机插拔