LeetCode 750. Number Of Corner Rectangles
Posted dylan-java-nyc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 750. Number Of Corner Rectangles相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/number-of-corner-rectangles/
题目:
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 grid[1][2], grid[1][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 either0
or1
. - The number of
1
s in the grid will be at most6000
.
题解:
When there is a new row, within this row, row[c1] and row[c2] are both 1.
Then number of newly constructed rectanges are number of previous rows having both exact same two columns mark as 1.
To maintain number of two 1 on c1 and c2, use a hash function c1*200+c2.
Time Complexity: O(r*c^2). r = grid.length. c = grid[0].length.
Space: O(c^2).
AC Java:
1 class Solution 2 public int countCornerRectangles(int[][] grid) 3 int res = 0; 4 HashMap<Integer, Integer> hm = new HashMap<>(); 5 for(int [] row : grid) 6 for(int c1 = 0; c1<row.length; c1++) 7 if(row[c1] == 1) 8 for(int c2 = c1+1; c2<row.length; c2++) 9 if(row[c2] == 1) 10 int hash = c1*200+c2; 11 int count = hm.getOrDefault(hash, 0); 12 res += count; 13 hm.put(hash, count+1); 14 15 16 17 18 19 20 return res; 21 22
以上是关于LeetCode 750. Number Of Corner Rectangles的主要内容,如果未能解决你的问题,请参考以下文章
750. Number Of Corner Rectangles四周是点的矩形个数
LeetCode --- 1128. Number of Equivalent Domino Pairs 解题报告
LeetCode --- 1128. Number of Equivalent Domino Pairs 解题报告
LeetCode 673. Number of Longest Increasing Subsequence 最长递增子序列的个数 (C++/Java)
[LeetCode] 1128. Number of Equivalent Domino Pairs 等价多米诺骨牌对的数量