当前位置:网站首页>【LeetCode】Day95-有效的数独&矩阵置零
【LeetCode】Day95-有效的数独&矩阵置零
2022-07-05 06:13:00 【倒过来是圈圈】
题目1
题解
如果按照规则行、列、3*3矩阵挨个试的话,工作量巨大…所以怎么才能降低复杂度呢?是这道题要重点考虑的问题
可以使用哈希表记录每一行、每一列和每一个小九宫格中,每个数字出现的次数。只需要遍历数独一次,在遍历的过程中更新哈希表中的计数,并判断是否满足有效的数独的条件即可。
class Solution {
public boolean isValidSudoku(char[][] board) {
int rows[][]=new int[9][9];//行
int columns[][]=new int[9][9];//列
int three[][][]=new int[3][3][9];//小九宫格
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
if(board[i][j]!='.'){
int index=board[i][j]-'0'-1;//字符转换为数字
rows[i][index]++;
columns[index][j]++;
three[i/3][j/3][index]++;//注意怎么表示小九宫格的哈希表
if(rows[i][index]>1||columns[index][j]>1||three[i/3][j/3][index]>1)
return false;
}
}
}
return true;
}
}
时间复杂度: O ( 1 ) O(1) O(1),数独大小是固定的,因此复杂度为O(1)
空间复杂度: O ( 1 ) O(1) O(1),由于数独大小固定,因此哈希表大小也固定,复杂度为O(1)
题目2
题解
使用两个数组row[]和column[]标记哪行哪列有0
class Solution {
public void setZeroes(int[][] matrix) {
int m=matrix.length,n=matrix[0].length;
boolean[] row=new boolean[m];
boolean[] column=new boolean[n];
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
//元素为0,行列打标记
if(matrix[i][j]==0){
row[i]=true;
column[j]=true;
}
}
}
//根据标记,行列赋零
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(row[i]==true||column[j]==true)
matrix[i][j]=0;
}
}
}
}
时间复杂度: O ( m n ) O(mn) O(mn)
空间复杂度: O ( m + n ) O(m+n) O(m+n)
边栏推荐
- Redis publish subscribe command line implementation
- Daily question 1984 Minimum difference in student scores
- Flutter Web 硬件键盘监听
- Dichotomy, discretization, etc
- 1996. number of weak characters in the game
- Implement a fixed capacity stack
- Brief introduction to tcp/ip protocol stack
- leetcode-9:回文数
- Time of process
- 【Rust 笔记】16-输入与输出(下)
猜你喜欢
1.15 - 输入输出系统
Data visualization chart summary (II)
R language [import and export of dataset]
Scope of inline symbol
MIT-6874-Deep Learning in the Life Sciences Week 7
Traditional databases are gradually "difficult to adapt", and cloud native databases stand out
数据可视化图表总结(二)
LVS简介【暂未完成(半成品)】
4. 对象映射 - Mapping.Mapster
Dichotomy, discretization, etc
随机推荐
[practical skills] technical management of managers with non-technical background
Simple knapsack, queue and stack with deque
leetcode-22:括号生成
Sqlmap tutorial (II) practical skills I
Collection: programming related websites and books
Introduction to LVS [unfinished (semi-finished products)]
LeetCode 0108. Convert an ordered array into a binary search tree - the median of the array is the root, and the left and right of the median are the left and right subtrees respectively
leetcode-1200:最小绝对差
Scope of inline symbol
Introduction et expérience de wazuh open source host Security Solution
Leetcode-6109: number of people who know secrets
Leetcode-31: next spread
[rust notes] 14 set (Part 2)
1041 Be Unique
MIT-6874-Deep Learning in the Life Sciences Week 7
Is it impossible for lamda to wake up?
Bit mask of bit operation
Navicat连接Oracle数据库报错ORA-28547或ORA-03135
JS quickly converts JSON data into URL parameters
快速使用Amazon MemoryDB并构建你专属的Redis内存数据库