C++ with 2 pointers


  • 0
    C

    The code explains itself.

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            if (nums.empty()) {
                return 0;
            }
            vector<int>::iterator p1 = nums.begin();
            vector<int>::iterator p2 = p1 + 1;
            while (p2 != nums.end()) {
                if (*p1 != *p2) {
                    *(++p1) = *(p2++);
                } else {
                    p2++;
                }
            }
            return p1 + 1 - nums.begin();
        }   
    };
    

Log in to reply
 

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