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

  • 1

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

    class Solution {
        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])
            return cnt;

Log in to reply

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