Leetcode(8) - remove duplicates in sorted array

Given a sorted array, you need to remove duplicate elements in place so that each element occurs only once, and return the new length of the removed array.

Instead of using extra array space, you have to modify the input array in- place and do it with O(1) extra space.

We use the existing interface of vector in STL to perfectly implement this function, the code is as follows

int removeDuplicates(vector<int>& nums) 
{
    nums.erase(unique(nums.begin(),nums.end()),nums.end());
    return nums.size();
}

The unique function can leave only one adjacent repeated elements in the container, and put the rest into the back of the vector, and the return value is the tail address of the container after deduplication. We also need to use the erase function to remove the following duplicate elements, and finally return the size of the container.

The above method is concise and perfect, but after all, it is an internal interface in STL. We still have to think about how to implement this function internally without using extra space.

class Solution {
public:
    int removeDuplicates(vector<int>& nums) 
    {
       int count=0;
        for(int i=1;i<nums.size();i++)
        {
            if(nums[i]==nums[i-1])
                count++;
            else
                nums[i-count]=nums[i];
        }
        return nums.size()-count;
    }
};

This is a lot more mundane, but it also looks more down-to-earth. The core counts the number of repeated elements while traversing, and the assignment operation of nums[i-count]=nums[i].

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325211648&siteId=291194637