[LeetCode] 1582. Special Positions in a Binary Matrix

Given an m x n binary matrix mat, return the number of special positions in mat.

A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).

Example 1:
Example 1
Input: mat = [[1,0,0],[0,0,1],[1,0,0]]
Output: 1
Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.

Example 2:
Example 2
Input: mat = [[1,0,0],[0,1,0],[0,0,1]]
Output: 3
Explanation: (0, 0), (1, 1) and (2, 2) are special positions.

Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 100
mat[i][j] is either 0 or 1.

二进制矩阵中的特殊位置。

给你一个大小为 rows x cols 的矩阵 mat,其中 mat[i][j] 是 0 或 1,请返回 矩阵 mat 中特殊位置的数目 。
特殊位置 定义:如果 mat[i][j] == 1 并且第 i 行和第 j 列中的所有其他元素均为 0(行和列的下标均 从 0 开始 ),则位置 (i, j) 被称为特殊位置。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/special-positions-in-a-binary-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

题意是找二进制矩阵中的特殊位置。这个特殊位置的定义是如果当前坐标值是1且他是当前行和当前列唯一的1,则当前位置就是一个特殊位置。

这道题不涉及算法,思路是需要扫描两遍矩阵。第一遍扫描的时候我们需要额外创建两个数组,一个记录当前行有多少个1,一个记录当前列有多少个1。第二遍扫描的时候,再碰到1的时候,我们就去看这个位置所在的行和所在的列是不是都只有一个1,如果是,则说明这是一个满足题意的特殊位置。

复杂度

时间O(mn)
空间O(n)

代码

Java实现

class Solution {
    public int numSpecial(int[][] mat) {
        HashMap<Integer, Integer> rowMap = new HashMap<>();
        HashMap<Integer, Integer> colMap = new HashMap<>();
        int m = mat.length;
        int n = mat[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 1) {
                    rowMap.put(i, rowMap.getOrDefault(i, 0) + 1);
                    colMap.put(j, colMap.getOrDefault(j, 0) + 1);
                }
            }
        }

        int count = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (mat[i][j] == 1 && rowMap.get(i) == 1 && colMap.get(j) == 1) {
                    count++;
                }
            }
        }
        return count;
    }
}
posted @ 2020-11-14 00:58  CNoodle  阅读(302)  评论(0编辑  收藏  举报