算法的重要性,我就不多說了吧,想去大廠,就必須要經過基礎知識和業務邏輯面試+算法面試。所以,為了提高大家的算法能力,這個公眾號後續每天帶大家做一道算法題,題目就從LeetCode上面選 !
今天和大家聊的問題叫做 有效的數獨,我們先來看題面:
https://leetcode-cn.com/problems/valid-sudoku/
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:Each row must contain the digits 1-9 without repetition.Each column must contain the digits 1-9 without repetition.Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.題意判斷一個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1-9 在每一個以粗實線分隔的 3x3 宮內只能出現一次。樣例題解這題主要是考察HashSet,不可保存重複元素。我們可以用3HashSet,分別保存第i行、第i列和第i個3x3的九宮格中的元素,每處理一個元素,若不為空,將正在處理的當前元素,添加到所屬的行、列以及3x3的九宮格中,若添加失敗,表明所屬的行、列或者3x3九宮格中有重複元素,返回false;若全部掃描完,返回true。class Solution {
public boolean isValidSudoku(char[][] board) {
//最外層循環,每次循環並非只是處理第i行,而是處理第i行、第i列以及第i個3x3的九宮格
for(int i = 0; i < 9; i++){
HashSet<Character> line = new HashSet<>();
HashSet<Character> col = new HashSet<>();
HashSet<Character> cube = new HashSet<>();
for(int j = 0; j < 9; j++){
if('.' != board[i][j] && !line.add(board[i][j]))
return false;
if('.' != board[j][i] && !col.add(board[j][i]))
return false;
int m = i/3*3+j/3;
int n = i%3*3+j%3;
if('.' != board[m][n] && !cube.add(board[m][n]))
return false;
}
}
return true;
}
}