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
.给定一个按非递减顺序排序的整数数组 nums
,就地删除重复项,使每个唯一元素只出现一次。元素的相对顺序应保持不变。然后返回 nums
中唯一元素的数量。
考虑 nums
中唯一元素的数量为 k
。为了通过验证,你需要做以下事情:
nums
,使得 nums
的前 k
个元素包含最初在 nums
中出现的唯一元素。nums
的剩余元素不重要,nums
的大小也不重要。k
。Example 1:
nums = [1,1,2]
2
, nums = [1,2,_]
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 2:
nums = [0,0,1,1,1,2,2,3,3,4]
5
, nums = [0,1,2,3,4,_,_,_,_,_]
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).约束条件:
1 <= nums.length <= 3 * 10^4
-100 <= nums[i] <= 100
nums
is sorted in non-decreasing order.双指针方法。
初始化两个指针:
遍历数组:
更新数组长度:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
// 非降序数组,原地移除重复出现的元素,保证每个元素只出现一次。
// 即 原地移除与前面位置相等的元素
int index = -1;
for (int i = 0; i < nums.size(); i++) {
if (i == 0 || nums[i - 1] != nums[i]) {
nums[++index] = nums[i];
}
}
return index + 1;
}
};