判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 '.' 表示。
示例 1:
输入:
[
["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
输出: true
示例 2:
输入:
[
["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]
输出: false
解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。
但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
说明:
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
给定数独序列只包含数字 1-9 和字符 '.' 。
给定数独永远是 9x9 形式的。
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
//可改进:vector用map代替,省略了初始化0的时间
vector<vector<int>>rowCol(18,vector<int>(10,0));//i=0~8表示i行,j=9~17表示j列
vector<vector<int>>nine(9,vector<int>(10,0));//九个3x3宫格,根据helper+行列数得到对应九小宫格序号
for(int i=0;i<9;++i)
for(int j=0;j<9;++j){
if(board[i][j]=='.')continue;
int val=board[i][j]-'0';
int hel=helper(i,j);
if(rowCol[i][val]==1||rowCol[9+j][val]==1||nine[hel][val]==1)return false;
rowCol[i][val]=1;
rowCol[9+j][val]=1;
nine[hel][val]=1;
}
return true;
}
int helper(int row,int col){//可改进:return row/3*3+col/3
int a,b;
if(row<=2)a=0;
else if(row<=5)a=3;
else a=6;
b=col/3;
return a+b;
}
};
给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数。
示例 1:
输入: [1,2,0]
输出: 3
示例 2:
输入: [3,4,-1,1]
输出: 2
示例 3:
输入: [7,8,9,11,12]
输出: 1
提示:
你的算法的时间复杂度应为O(n),并且只能使用常数级别的额外空间。
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
int nSize=nums.size();
if(nSize==0)return 1;
int inValid=nSize+1;//统一无效值
for(int i=0;i<nSize;++i)
if(nums[i]<=0||nums[i]>nSize)nums[i]=inValid;
for(int i=0;i<nSize;++i){
int x=abs(nums[i]);
if(x>0&&x<=nSize){//有效值置负
nums[x-1]=-abs(nums[x-1]);
}
}
for(int i=0;i<nSize;++i)
if(nums[i]>0)return i+1;//正数则为所求结果
return nSize+1;
}
};