Both 5ms C++ code accepted, what is the difference?


  • 0
    L

    First:

    class Solution {
    public:
        int removeElement(int A[], int n, int elem) {
             int count = 0;
                for (int i = 0; i < n; ++i)
                {
                    if (A[i] != elem)
                    {
                        A[count++] = A[i];
                    }
                }
                return count;
        }
    };
    

    Second:
    
        class Solution {
    public:
        int removeElement(int A[], int n, int elem) {
             int count = 0;
                for (int i = 0; i < n; i++)
                {
                    if (A[i] != elem)
                    {
                        A[count++] = A[i];
                    }
                }
                return count;
        }
    };

  • 0
    C

    Prefix increment of i in the for loop.

    Prefix is garuanteed to be the same as or faster than postfix.
    Afaik this would be because postfix must construct and return a copy of i, which may be more expensive than the reference which prefix returns.


  • 0
    L

    Great. So it looks prefix may be better.
    Is there any functionality difference? Could we replace postfix using prefix in every 'for loop'?


  • 0
    C

    In the for loop, yes. Prefix is a good habit.

    To clarify the difference:

    Prefix:

    int i = 0;

    cout << ++i; //Prints '1' using a reference to i. (i.e. the value is "fixed" first)

    // i is 1

    Postfix:

    int i = 0;

    cout << i++; //Prints '0' using a copy of what i was. (i.e. the value is "fixed" afterwards)

    // i is 1


Log in to reply
 

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