Remove Duplicates From a Sorted Array
Problem
A sorted array may contain repeats. Compact it in place so the first portion holds each distinct value exactly once, in original order, and return the new length. Values past the new length don't matter.
Two pointers: a write index w marks where the next unique value belongs; a read index r scans the array. Only when the new value differs from the previous kept one do we copy and advance w.
Input
nums = [1, 1, 2, 3, 3, 3, 5]Output
4, nums starts with [1, 2, 3, 5, …]def remove_duplicates(nums):
if not nums:
return 0
w = 1
for r in range(1, len(nums)):
if nums[r] != nums[w - 1]:
nums[w] = nums[r]
w += 1
return w
function removeDuplicates(nums) {
if (nums.length === 0) return 0;
let w = 1;
for (let r = 1; r < nums.length; r++) {
if (nums[r] !== nums[w - 1]) {
nums[w] = nums[r];
w++;
}
}
return w;
}
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length == 0) return 0;
int w = 1;
for (int r = 1; r < nums.length; r++) {
if (nums[r] != nums[w - 1]) {
nums[w++] = nums[r];
}
}
return w;
}
}
int removeDuplicates(vector<int>& nums) {
if (nums.empty()) return 0;
int w = 1;
for (int r = 1; r < (int)nums.size(); r++) {
if (nums[r] != nums[w - 1]) {
nums[w++] = nums[r];
}
}
return w;
}