348. Design Tic-Tac-Toe
Naive n^2
T: move() : O(n^2)
S: O(n^2)
class TicTacToe {
private int[][] board;
private int n;
public TicTacToe(int n) {
board = new int[n][n];
this.n = n;
}
public int move(int row, int col, int player) {
board[row][col] = player == 1 ? 1 : -1;
int diagnal = 0;
int antiDiagnal = 0;
int result = 0;
for (int i = 0; i < n; i++) {
int rowResult = 0;
int colResult = 0;
for (int j = 0; j < n; j++) {
rowResult += board[i][j];
colResult += board[j][i];
}
diagnal += board[i][i];
antiDiagnal += board[i][n-1-i];
if (Math.abs(rowResult) == n) {
return board[i][0] == 1 ? 1 : 2;
}
if (Math.abs(colResult) == n) {
return board[0][i] == 1 ? 1 : 2;
}
}
if (Math.abs(diagnal) == n) {
return board[0][0] == 1 ? 1 : 2;
}
if (Math.abs(antiDiagnal) == n) {
return board[0][n-1] == 1 ? 1 : 2;
}
return 0;
}
}
/**
00 1 02
1 2
20 22
00 01 02 03
10 11 12 13
20 21 22 23
30 31 32 33
* Your TicTacToe object will be instantiated and called as such:
* TicTacToe obj = new TicTacToe(n);
* int param_1 = obj.move(row,col,player);
*/O(1) solution
其實我們關心的是整 row, or 整 col, 每次新的 move 都加在之前結果上就可以決定是不是 win 了
所以紀錄整 row 的總和, 整個 col 的總和即可, 不用每次都整個重算
T: move(): O(1)
S: O(n)
Last updated
Was this helpful?