LeetCode 36 Valid Sudoku (O(1)空间 位运算)
来源:互联网 发布:淘宝怎么注册天猫 编辑:程序博客网 时间:2024/06/07 23:05
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
题目分析:由于一次最多只需要检查9个数字,1 << 9 < INT_MAX,因此可以用整型数字的二进制位来判断某个数字是否出现过,击败95%
public class Solution { public boolean isValidSudoku(char[][] board) { int mask = 0, num = 0; for (int i = 0; i < 9; i ++) { mask = 0; for (int j = 0; j < 9; j ++) { if (board[i][j] != '.') { num = board[i][j] - '0'; if ((mask & (1 << num)) == 0) { mask |= (1 << num); } else { return false; } } } } for (int j = 0; j < 9; j ++) { mask = 0; for (int i = 0; i < 9; i ++) { if (board[i][j] != '.') { num = board[i][j] - '0'; if ((mask & (1 << num)) == 0) { mask |= (1 << num); } else { return false; } } } } for (int i = 0; i < 3; i ++) { for (int j = 0; j < 3; j ++) { int x = i * 3; int y = j * 3; mask = 0; for (int k = 0; k < 3; k ++) { for (int l = 0; l < 3; l ++) { if (board[x + k][y + l] != '.') { num = board[x + k][y + l] - '0'; if ((mask & (1 << num)) == 0) { mask |= (1 << num); } else { return false; } } } } } } return true; }}
阅读全文
0 0
- LeetCode 36 Valid Sudoku (O(1)空间 位运算)
- LeetCode-36-Valid Sudoku 位运算状压,python的ascll,char互转
- [leetcode 36] Valid Sudoku
- leetcode 36: Valid Sudoku
- LeetCode(36) Valid Sudoku
- leetcode-36 Valid Sudoku
- Valid Sudoku - LeetCode 36
- LeetCode 36 Valid Sudoku
- LeetCode---(36) Valid Sudoku
- Leetcode 36 Valid Sudoku
- Leetcode[36]-Valid Sudoku
- leetcode 36: Valid Sudoku
- Leetcode# 36 Valid Sudoku
- Leetcode#36||Valid Sudoku
- leetcode-36 Valid Sudoku
- leetcode 36:Valid Sudoku
- LeetCode 36: Valid Sudoku
- [leetcode 36] Valid Sudoku
- iOS 给NSString文字中间或底部添加横线
- 串口通信中波特率
- js的一些兼容性写法
- 让Apache Shiro保护你的应用
- 欢迎使用CSDN-markdown编辑器
- LeetCode 36 Valid Sudoku (O(1)空间 位运算)
- Spring boot和Mybatis整合+Mysql+jsp页面跳转问题(借助FreeMarker)
- Binder.clearCallingIdentity && Binder.restoreCallingIdentity作用
- 人脸检测——AFLW准备人脸
- google翻译的用法 使用translate.google.com翻译整个网页内容
- ipython notebook实用教程
- Could not find a storyboard named 'Main' in bundle NSBundle?
- 【好久不见】捡起mysql的存储过程
- 根据域名动态获取IP地址(iOS)