26. Remove Duplicates from Sorted Array
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]Intuition
Approach
Complexity
Code
Space Complexity
Time Complexity
Last updated
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]Last updated
public int removeDuplicates(int[] nums) {
int j = 0;
for (int i = 0; i < nums.length; ++i) {
// If the element are not equal only then add to array
if(nums[i] != nums[j]) {
nums[++j] = nums[i];
}
}
return j+1;
}public int removeDuplicates(int[] nums) {
int shiftPlacesBy = 0;
for (int i = 1; i < nums.length; ++i) {
// if elements are equal we increase the shift count by
if(nums[i] == nums[i-1]) {
shiftPlacesBy++;
continue;
}
nums[i - shiftPlacesBy] = nums[i];
}
return nums.length - shiftPlacesBy;
}