Created
June 24, 2020 18:42
-
-
Save nihal-singh/7429e655800599873da52292fea9808b to your computer and use it in GitHub Desktop.
Code Solutions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Author
nihal-singh
commented
Jun 24, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment