今年的谷歌不是放水,是“泄洪”
最近有人发现,Google的bar低出了新高度,面试题难度远不如以前,成功跳槽狗家的求职者更是一个接一个。
虽然谷歌新题多,喜欢follow up,但平时多精刷高频题和变形题,掌握解题思路,拿下offer也不是难事。
一道谷歌常考算法题,带你了解面试难度:
LintCode 1310
统计全为1的正方形全矩阵
题目描述 给你一个 m * n 的矩阵,矩阵中的元素不是 0 就是 1,请你统计并返回其中完全由 1 组成的 正方形 子矩阵的个数。- 1 <= arr.length <= 300
- 1 <= arr[0].length <= 300
题目描述
1 <= arr.length <= 300
1 <= arr[0].length <= 300
扫码免费做题 ↓↓↓
样例 1
输入:
matrix =
[
[0,1,1,1],
[ ],
[ ]
]
输出:
15
解释:
边长为 1 的正方形有 10 个。
边长为 2 的正方形有 4 个。
边长为 3 的正方形有 1 个。
正方形的总数 = 10 + 4 + 1 = 15.
样例 2
输入:
matrix =
[
[1,0,1],
[ ],
[ ]
]
输出:
7
解释:
边长为 1 的正方形有 6 个。
边长为 2 的正方形有 1 个。
正方形的总数 = 6 + 1 = 7.
解法/算法
动态规划
解题思路
根据dp数组来记录以下标为 i, j 的点左上角的的最长的正方形边长。
复杂度分析
时间复杂度:O(n * m)
n为数组行数,m为数组列数。
空间复杂度:O(n * m)
n为数组行数,m为数组列数。
源代码
publicclassSolution{
/**
* @param matrix: a matrix
* @return: return how many square submatrices have all ones
*/
publicintcountSquares(int[][] matrix){
int row = matrix.length, col = matrix[0].length, answer = 0;
int[][] dp = newint[row][col];
for(int i = 0;i < row;i++){
for(int j = 0;j < col;j++){
if(i == 0 || j == 0){
dp[i][j] = matrix[i][j];
}
elseif(matrix[i][j] == 0){
dp[i][j] = 0;
}
else{
dp[i][j] = Math.min(Math.min(dp[i][j - 1], dp[i - 1][j]), dp[i - 1][j - 1]) + 1;
}
answer += dp[i][j];
}
}
return answer;
}
}
点击【阅读原文】,查看领扣原题。
阅读原文 关键词
矩阵
正方形
思路
最新评论
推荐文章
作者最新文章
你可能感兴趣的文章
Copyright Disclaimer: The copyright of contents (including texts, images, videos and audios) posted above belong to the User who shared or the third-party website which the User shared from. If you found your copyright have been infringed, please send a DMCA takedown notice to [email protected]. For more detail of the source, please click on the button "Read Original Post" below. For other communications, please send to [email protected].
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。
版权声明:以上内容为用户推荐收藏至CareerEngine平台,其内容(含文字、图片、视频、音频等)及知识版权均属用户或用户转发自的第三方网站,如涉嫌侵权,请通知[email protected]进行信息删除。如需查看信息来源,请点击“查看原文”。如需洽谈其它事宜,请联系[email protected]。