Java - in-place O(1), O(n)


  • 0
    J
    public class Solution {
    public static void main(String[] args) {
    	Solution sol = new Solution();
    	sol.removeDuplicates(new int[] { 1, 1, 1, 2 });
    }
    
    public int removeDuplicates(int[] nums) {
    	if (nums.length < 2)
    		return nums.length;
    
    	int i = 0, len = 0;
    	while (i < nums.length) {
    		if (len < i) {
    			nums[len++] = nums[i++];
    		} else {
    			i++;
    			len++;
    		}
    		int j = i;
    		while (j < nums.length && nums[j] == nums[i - 1]) {
    			j++;
    		}
    		if (j - i > 0) {
    			nums[len++] = nums[i++];
    		}
    		i = j;
    	}
    	return len;
    }
    

    }


Log in to reply
 

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