java solution for at most k times duplication


  • 0

    almost the same with Remove Duplicate, but to record the times of duplication while processing.

    private static int dup = 2;
    	
    	public int removeDuplicates(int[] nums) {
    		if (nums == null || nums.length == 0)
    			return 0;
    		
    		int t = 0, i = 0, j = 0;
    		while (j < nums.length) {
    			if (t == dup) {
    				while (j < nums.length && nums[j] == nums[j - 1]) j ++;
    				if (j == nums.length) break;
    			}
    			nums[i] = nums[j];
    			if (i == 0 || nums[i] != nums[i - 1])
    				t = 1;
    			else t ++;
    			i ++; j ++;
    		}
    		return i;
    	}

Log in to reply
 

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