Why is the code 2 times faster by merely changing +=n to ++ ?


  • 0
    A

    My original Island Perimeter solution only beats 15% submission, so I went to see the leading solutions.

    Unfortunately I did not see any big difference, such as using different functions or loops. The only differences I recognize are:

    1. The leading solutions use count++ and return count4*, while I use count+=4 and return count
    2. The leading solutions use if(a==1), while I use if(a)

    I applied my code with the first method, and beat 90% submission immediately. Seems the differences really counts, but I do not know why.

    Bellow is my original solution, which takes 199ms, beats 15%

        int islandPerimeter(vector<vector<int>>& grid) {
            if (grid.size() <= 0) return 0;
            int perimeter = 0;
            for (int j=0; j<grid.size(); j++) {
                for (int i=0; i<grid[j].size(); i++) {
                    if (grid[j][i]) {
                        perimeter += 4;
                        if (j > 0 && grid[j-1][i]) perimeter -= 2;
                        if (i > 0 && grid[j][i-1]) perimeter -= 2;
                    }
                }
            }
            return perimeter;
        }
    

    And this is the one I applied the first method, which takes 129ms, beats 92%

    int islandPerimeter(vector<vector<int>>& grid) {
            if (grid.size() <= 0) return 0;
            int perimeter = 0;
            int overlap = 0;
            for (int j=0; j<grid.size(); j++) {
                for (int i=0; i<grid[j].size(); i++) {
                    if (grid[j][i]) {
                        perimeter++;
                        if (j > 0 && grid[j-1][i]) overlap++;
                        if (i > 0 && grid[j][i-1]) overlap++;
                    }
                }
            }
            return perimeter*4-overlap*2;
        }
    

    Could anyone please explain the why ++ outperforms +=n ?


Log in to reply
 

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