O(n) time O(1) space


  • 0

    ublic class Solution {
    public int removeDuplicates(int[] nums) {
    if (nums == null || nums.length == 0){
    return 0;
    }
    int prev = nums[0];
    int count = 1;
    int dup = 0;
    for (int i = 1; i < nums.length; i++){
    int currNum = nums[i];
    if (currNum != prev){
    if (dup != 0){
    swap(i,dup,nums);
    dup++;
    }
    prev = currNum;
    count++;
    }
    else{
    if (dup == 0){
    dup = i;
    }
    }
    }
    return count;
    }

    private void swap(int i , int j , int[] nums){
        nums[j] = nums[i];
    }
    

    }


Log in to reply
 

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