remove duplicates from sorted array tutorial code example
Example 1: remove duplicates from sorted array
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;
}
Example 2: remove duplicates in sorted array python
j = 0
for i=0 to n-2
if arr[i] != arr[i+1]
arr[j] = arr[i]
j += 1
arr[j] = arr[n-1]
j += 1
for i=0 to j-1
print arr[i]
Example 3: remove duplicates from sorted array
def remove_duplicates(nums: [int]) -> int:
cnt = 1
for index in range(len(nums) - 1):
if nums[index] != nums[index + 1]:
nums[cnt] = nums[index + 1]
cnt += 1
print(cnt)