转载

每周学算法/读英文/知识点心得分享 9.19

 每周一个 Algorithm,Review 一篇英文文章,总结一个工作中的技术 Tip,以及 Share 一个传递价值观的东西!

Algorithm: 学习算法

题目:valid-sudoku(有效的数独)

描述:判断一个 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

说明:

  • 一个有效的数独(部分已被填充)不一定是可解的。
  • 只需要根据以上规则,验证已经填入的数字是否有效即可。
  • 给定数独序列只包含数字 1-9 和字符 '.' 。
  • 给定数独永远是 9x9 形式的

 

解题过程:

利用 set 不重复保存的特性,将数独元素存入set中,如果不能保存,就判断为无效。

精髓是给数字按不同维度标记。因为要数字不重复, 那么可以给每个数字在 行、列、九宫格 里 分别给到不同的标识,比如 

  • 第四行的7,记为"(7) in line 4"
  • 第四列的7,记为"(7) in column 4"
  • 在右上角的九宫格的7,记为"(7) in (0,3)"

解法:

 

 1 import java.util.HashSet;
 2 import java.util.Set;
 3 
 4 /**
 5  * description : https://leetcode.com/problems/valid-sudoku/
 6  * 题目描述 : https://leetcode-cn.com/problems/valid-sudoku/
 7  */
 8 public class ValidSudoku {
 9 
10     public boolean isValidSudoku(char[][] board) {
11         Set seen = new HashSet();
12         for (int i = 0; i < 9; ++i) {
13             for (int j = 0; j < 9; ++j) {
14                 char number = board[i][j];
15                 if (number != '.')
16                     if (!seen.add(number + " in row " + i) ||
17                             !seen.add(number + " in column " + j) ||
18                             !seen.add(number + " in block " + i / 3 + "-" + j / 3))
19                         return false;
20             }
21         }
22         return true;
23     }
24 }
ValidSudoku

 

Review: 学习英文

题目:

 

Tips: 知识点

如何在linux服务器 后台运行一个程序?

参考这篇文章 :Linux命令之nohup 和 重定向

 

Share: 价值观

 

转载于:https://www.cnblogs.com/andrew-chen/p/11541556.html

正文到此结束
本文目录