给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
两数之和
初级算法 - LeetBook - 力扣(LeetCode)全球极客挚爱的技术成长平台编辑
思路一:暴力解法,拟双指针遍历数组寻找匹配的位置返回
class Solution { public int[] twoSum(int[] nums, int target) { int[] temp = new int[2]; for (int i = 0; i < nums.length-1; i++) { for (int j = i+1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { temp[0] = i; temp[1] = j; return temp; } } } return temp; } }
有效的数独
初级算法 - LeetBook - 力扣(LeetCode)全球极客挚爱的技术成长平台
请你判断一个 9 x 9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
注意:
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
空白格用 '.' 表示。
编辑
输入:board =
[["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:
输入:board =
[["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 存在, 因此这个数独是无效的。
提示:
board.length == 9
board[i].length == 9
board[i][j] 是一位数字(1-9)或者 '.'
相关标签
Java
思路一:确定数独是否合理需要三个条件,1.每一行每一个数字只能出现一次。2.每一列每一个数字只能出现一次。3.每一个3*3的对应格子内每一个数字只能出现一次。这样我们用三个数组分别表示行,列,对应格子,里面存放每一个数字出现的次数,如果一个数字在这三个数组出现过就返回false不满足,如果所有元素都通过就说明满足条件
class Solution { public boolean isValidSudoku(char[][] board) { //创建行数字统计,二维数组的第一个框表示第几行第二个框内是1——9这些数字,而这个数组值表示这个数组在行内出现的次数 int[][] line=new int[board.length][board[0].length]; //创建列数字统计 int[][] col=new int[board.length][board[0].length]; //创建对应格子的序列 int[][] box=new int[board.length][board[0].length]; //num是遍历的元素的值 int num=-1; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length ; j++) { if(board[i][j]=='.') { continue; } //num如果到达了9会越界,所以我们将每一个数字减一1-9就变成0-8去记录,不影响结果 num=board[i][j]-'1'; //box是对应的3*3的格子的序列号 int box_Index=i/3*3+j/3; //初始new的数组每一个数字出现的次数都是0,如果为1说明这个数字出现过 if(line[i][num]==1) { return false; } if(col[j][num]==1) { return false; } if(box[box_Index][num]==1) { return false; } //这里说明这个数字没有出现过所以记录数字 line[i][num]=1; col[j][num]=1; box[box_Index][num]=1; } } return true; } }