My solution in c++

  • -2
    int removeDuplicates(vector<int>& nums) {
        for (int i = 1; i < nums.size(); ){
            if (nums[i] == nums[i - 1])
                nums.erase(nums.begin() + i);
        return nums.size();

  • 0

    Note that erase is not an efficient operation. Check this link

    Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list)

  • 0

    Thank you for the comment!

    I did not notice the requirement in the question "Do not allocate extra space for another array, you must do this in place with constant memory."

Log in to reply

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