Remove Duplicates from Sorted Array

Remove Duplicates from Sorted Array

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Solution1

Two Pointers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}

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