Performance when resizing vector


  • 0
    H

    I just wanted to share that the following code,

    class TicTacToe {
    public:
        vector<int> row;
        vector<int> col;
        int diagonal;
        int antiDiagonal;
        int n;
        /** Initialize your data structure here. */
        TicTacToe(int n) {
            row.resize(n, 0);
            col.resize(n, 0);
            diagonal = 0;
            antiDiagonal = 0;
            this->n = n;
        }
        
        /** Player {player} makes a move at ({row}, {col}).
            @param row The row of the board.
            @param col The column of the board.
            @param player The player, can be either 1 or 2.
            @return The current winning condition, can be either:
                    0: No one wins.
                    1: Player 1 wins.
                    2: Player 2 wins. */
        int move(int r, int c, int player) {
            int score;
            if(player == 1) score = 1;
            else score = -1;
            row[r] += score;
            col[c] += score;
            if(r == c) diagonal += score;
            if(r + c == n-1) antiDiagonal += score;
            if(abs(row[r]) == n || abs(col[c]) == n || abs(diagonal) == n || abs(antiDiagonal) == n) return player;
            return 0;
        }
    };
    

    Takes 63ms (beats 22.79%) and if I change the resize lines as,

    row.resize(n)
    col.resize(n)
    

    the time taken is only 42ms and beats 93.75% of the solutions. So looks like resize function initially fills the array with 0 by default. A good hack to get those runtimes down


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.