Share my 20ms C++ solution

  • 0

    The idea is that, to remove consecutive duplicate items starting from 2 indexes away till the furthest, and thus we only need to scan the vector only once. Then return the size of vector left.

    class Solution {
        int removeDuplicates(vector<int>& nums) {
            if (nums.size() <= 2) return nums.size();
            for (int i = 0; i < nums.size()-2; i++)
                int j = i + 2;
                while (j < nums.size() && nums[j] == nums[i])
                    nums.erase(nums.begin() + j);
            return nums.size();

Log in to reply

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