#26

Remove Duplicates from Sorted Array

pupil · 430 · lc easy +25 · verified · 62.3% accepted · 18,870 likes · top 63%

play →

Description

The non-decreasing integer array nums may contain duplicates. Remove them in-place so each distinct value appears exactly once, preserving sorted order. Return k, the count of unique values; the first k entries of nums must hold those values in order. Entries beyond index k are irrelevant.

Example 1:

int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length

Example 2:

int k = removeDuplicates(nums); // Calls your implementation

Example 3:

assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}

Example 4:

Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
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).

Example 5:

Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).

Code

1
2
3