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:
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.k.Custom Judge:
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.It does not matter what you leave beyond the returned k (hence they are underscores).
Explanation: Your function should return k = 4, with the first four elements of nums being 0, 1, 2, and 3 respectively. It does not matter what you leave beyond the returned k.
nums is sorted in non-decreasing order.In a sorted array, duplicates always appear next to each other.
This makes it easy to remove duplicates using a two-pointer technique:
Whenever we discover a new unique value, we move it to nums[writePos] and advance writePos.
All unique elements end up at the front of the array. Anything beyond writePos is irrelevant.
0 since no elements exist.writePos = 0, marking where the next unique element should be placed.readPos to scan from the second element onward.nums[readPos] is different from nums[writePos], we found a new unique element.writePos.nums[readPos] to nums[writePos].writePos + 1, the count of unique elements.