Remove Duplicates from Sorted Array
Last updated
Last updated
Given an integer array nums
sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums
.
Consider the number of unique elements of nums
to be k
, to get accepted, you need to do the following things:
Change the array nums
such that the first k
elements of nums
contain the unique elements in the order they were present in nums
initially. The remaining elements of nums
are not important as well as the size of nums
.
Return k
.
Custom Judge:
The judge will test your solution with the following code:
If all assertions pass, then your solution will be accepted.
Example 1:
Example 2:
Constraints:
1 <= nums.length <= 3 * 104
-100 <= nums[i] <= 100
nums
is sorted in non-decreasing order.
You can solve this problem by using two pointers. Here's a JavaScript implementation:
In this implementation, the removeDuplicates
function iterates through the array using two pointers. The uniqueIndex
pointer points to the last unique element found so far. If the current element is different from the element at the uniqueIndex
, it increments uniqueIndex
and updates nums[uniqueIndex]
with the current element. Finally, it returns the number of unique elements found.