Leetcode 26. Remove Duplicates from Sorted Array
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 length of the array part with unique elements as k
, where the first k
elements of nums
should hold the unique elements in order, with no concern about the elements in the remaining part of the array.
Do not allocate extra space for another array; you must do this by modifying the input array in-place with O(1) extra memory.
Input: nums = [1, 1, 2]
Output: 2, nums = [1, 2, _]
Explanation: Your function should return k = 2
, and the first two elements of nums
are 1
and 2
. It does not matter what you leave beyond the returned k
(hence they are underscores).
0
.k
elements are unique, with no constraints on the elements beyond this point.lastUniqueIndex
to 0 (this will track the index of the last unique element).nums[lastUniqueIndex]
, increment lastUniqueIndex
and update nums[lastUniqueIndex]
to the current element.lastUniqueIndex + 1
as the count of unique elements.#include <vector>
int removeDuplicates(std::vector<int>& nums) {
if (nums.empty()) return 0;
int lastUniqueIndex = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] != nums[lastUniqueIndex]) {
lastUniqueIndex++;
nums[lastUniqueIndex] = nums[i];
}
}
return lastUniqueIndex + 1;
}
n
is the length of the array. We traverse the array once.This approach ensures that only unique elements are kept in the first part of the array, maintaining the original order, and fulfilling the problem’s constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?