Skip to content

Instantly share code, notes, and snippets.

@nihal-singh
Created June 24, 2020 18:42
Show Gist options
  • Save nihal-singh/7429e655800599873da52292fea9808b to your computer and use it in GitHub Desktop.
Save nihal-singh/7429e655800599873da52292fea9808b to your computer and use it in GitHub Desktop.
Code Solutions
class Solution {
public int removeDuplicates(int[] nums) {
int len = nums.length; // calculate length of the array.
if(len == 0 || len == 1)return len; // return length if array has zero or only one element.
int lastMem = nums[0]; // stores the element that is not duplicate
int count = 1; //return count at last so as to get the unique element count
int index = 1;
/* Traverse the array from first to last and swap the element which is unique with the element in starting and increase the index.
*/
for (int i=1; i < len;i++){
if(nums[i] != lastMem){
lastMem = nums[i];
nums[index++] = lastMem;
count++;
}
}
return count;
}
}
@nihal-singh
Copy link
Author

nihal-singh commented Jun 24, 2020

public int removeDuplicates(int[] nums) {
    if (nums.length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment