Code Bases

  1. Remove duplicates from an sorted array (allow at most k duplicates)
    public int removeDuplicates(int[] nums) {
        return removeDuplicates(nums, 2);    
    }

    private int removeDuplicates(int[] nums, int k) {
        if (nums.length <= k)
            return nums.length;
        int index = k; 
        for (int i = k; i < nums.length; i++) {
            if (nums[i] != nums[index - k]) {
                //index++;
                nums[index++] = nums[i];
            }
        }
        return index;
    }