Leetcode – Remove Duplicates

Name: Remove Duplicates from Sorted Array
Difficulty: Easy
Description: Remove duplicates from a sorted array – in place

Example:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]

Should return the correct number (k) of unique numbers, the array should be in sorted order. After k numbers, the rest of the numbers are ignored. 
int removeDuplicates(vector<int>& nums) {
    if (nums.size() == 1) return 1;

    auto index = nums.begin() + 1;
    int last = *nums.begin();

    for(auto i = index; i < nums.end(); ++i) {
        if (*i != last) {
            last = *index++ = *i;
        }
    }

    return static_cast<int>(index - nums.begin());
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s