C++ concise and generalized solution for "remove duplicates"


  • 1
    M

    Given a sorted array, remove the duplicates in place such that each element appear only k times and return the new length.

    class Solution {
    public:
        int removeDuplicates(vector<int>& nums) {
            int k = 2;   // appear at most k times;
            
            if(nums.size() <= k)
                return nums.size();
            int cnt = k;
            for(int i = k; i < nums.size(); i++)
            {
                if(nums[i] != nums[cnt-k])
                    swap(nums[i],nums[cnt++]);
            }
            return cnt;
        }
    };

Log in to reply
 

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