1275. Find Winner on a Tic Tac Toe Game

寫法跟 348 大致差不多

T: O(n), n is length of moves

S: O(1)

class Solution {
    public String tictactoe(int[][] moves) {
        int[] row = new int[3];
        int[] col = new int[3];
        int diagnal = 0;
        int antiDianal = 0;
        
        for (int i = 0; i < moves.length; i++) {
            int value = i%2 == 0 ? 1 : -1;
            int r = moves[i][0];
            int c = moves[i][1];
            
            row[r] += value;
            col[c] += value;
            if (r == c) {
                diagnal += value;
            }
            if (r + c == 2) {
                antiDianal += value;
            }
            
            if (Math.abs(row[r]) == 3 || 
                Math.abs(col[c]) == 3 ||
                Math.abs(diagnal) == 3 ||
                Math.abs(antiDianal) == 3) {
                
                return value < 0 ? "B" : "A";
            }
        }
        
        if (moves.length == 9) {
            return "Draw";
        }
        
        return "Pending";
    }

}

Last updated