|
1 | 1 | --- |
2 | | -title: 1582.二进制矩阵中的特殊位置 |
| 2 | +title: 1582.二进制矩阵中的特殊位置:模拟/记录每行每列1个数/行有单1再看列 |
3 | 3 | date: 2022-09-04 14:59:22 |
4 | 4 | tags: [题解, LeetCode, 简单, 数组, 矩阵] |
5 | 5 | categories: [题解, LeetCode] |
6 | 6 | --- |
7 | 7 |
|
8 | | -# 【LetMeFly】1582.二进制矩阵中的特殊位置 |
| 8 | +# 【LetMeFly】1582.二进制矩阵中的特殊位置:模拟/记录每行每列1个数/行有单1再看列 |
9 | 9 |
|
10 | 10 | 力扣题目链接:[https://leetcode.cn/problems/special-positions-in-a-binary-matrix/](https://leetcode.cn/problems/special-positions-in-a-binary-matrix/) |
11 | 11 |
|
@@ -63,8 +63,6 @@ categories: [题解, LeetCode] |
63 | 63 | <li><code>mat[i][j]</code> 是 <code>0</code> 或 <code>1</code></li> |
64 | 64 | </ul> |
65 | 65 |
|
66 | | - |
67 | | - |
68 | 66 | ## 方法一:直接模拟 |
69 | 67 |
|
70 | 68 | 直接遍历一遍原始矩阵,如果当前元素是1,就判断是否这一行除此元素外都是0并且这一列除此元素外都是0。 |
@@ -147,5 +145,53 @@ public: |
147 | 145 | }; |
148 | 146 | ``` |
149 | 147 |
|
| 148 | +## 方法三:行有单1再看列 |
| 149 | + |
| 150 | +从第一行到最后一行遍历,对于每一行,若这一行只有一个1,则遍历1这一列,若这一列其他位置皆为0,则此1为特殊位置。 |
| 151 | + |
| 152 | ++ 时间复杂度$O(n(n+m))$,其中原始矩阵的大小为$n\times m$ |
| 153 | ++ 空间复杂度$O(1)$ |
| 154 | + |
| 155 | +### AC代码 |
| 156 | + |
| 157 | +#### C++ |
| 158 | + |
| 159 | +```cpp |
| 160 | +/* |
| 161 | + * @LastEditTime: 2026-03-05 00:02:09 |
| 162 | + */ |
| 163 | +class Solution { |
| 164 | +public: |
| 165 | + int numSpecial(vector<vector<int>>& mat) { |
| 166 | + int ans = 0; |
| 167 | + int n = mat.size(), m = mat[0].size(); |
| 168 | + for (int i = 0; i < n; i++) { |
| 169 | + bool only1 = true; |
| 170 | + int idx = -1; |
| 171 | + for (int j = 0; j < m; j++) { |
| 172 | + if (mat[i][j]) { |
| 173 | + if (idx != -1) { |
| 174 | + only1 = false; |
| 175 | + break; |
| 176 | + } |
| 177 | + idx = j; |
| 178 | + } |
| 179 | + } |
| 180 | + if (!only1 || idx == -1) { |
| 181 | + continue; |
| 182 | + } |
| 183 | + for (int k = 0; k < n; k++) { |
| 184 | + if (mat[k][idx] && k != i) { |
| 185 | + only1 = false; |
| 186 | + break; |
| 187 | + } |
| 188 | + } |
| 189 | + ans += only1; |
| 190 | + } |
| 191 | + return ans; |
| 192 | + } |
| 193 | +}; |
| 194 | +``` |
| 195 | +
|
150 | 196 | > 同步发文于CSDN,原创不易,转载请附上[原文链接](https://blog.letmefly.xyz/2022/09/04/LeetCode%201582.%E4%BA%8C%E8%BF%9B%E5%88%B6%E7%9F%A9%E9%98%B5%E4%B8%AD%E7%9A%84%E7%89%B9%E6%AE%8A%E4%BD%8D%E7%BD%AE/)哦~ |
151 | 197 | > Tisfy:[https://letmefly.blog.csdn.net/article/details/126689744](https://letmefly.blog.csdn.net/article/details/126689744) |
0 commit comments