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 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 firstk
elements ofnums
contain the unique elements in the order they were present innums
initially. The remaining elements ofnums
are not important as well as the size ofnums
. - Return
k
.
中文释义
给定一个按非递减顺序排序的整数数组 nums
,就地删除重复项,使每个唯一元素只出现一次。元素的相对顺序应保持不变。然后返回 nums
中唯一元素的数量。
考虑 nums
中唯一元素的数量为 k
。为了通过验证,你需要做以下事情:
- 修改数组
nums
,使得nums
的前k
个元素包含最初在nums
中出现的唯一元素。nums
的剩余元素不重要,nums
的大小也不重要。 - 返回
k
。
示例
Example 1:
- Input:
nums = [1,1,2]
- Output:
2
,nums = [1,2,_]
- Explanation: Your function should return
k = 2
, with the first two elements ofnums
being1
and2
respectively. It does not matter what you leave beyond the returnedk
(hence they are underscores).
Example 2:
- 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 ofnums
being0
,1
,2
,3
, and4
respectively. It does not matter what you leave beyond the returnedk
(hence they are underscores).
约束条件:
1 <= nums.length <= 3 * 10^4
-100 <= nums[i] <= 100
nums
is sorted in non-decreasing order.
解题思路
方法
双指针方法。
步骤
-
初始化两个指针:
- index(慢指针):用于在数组中构建不重复的新数组。
- i(快指针):用于遍历原数组。
-
遍历数组:
- 遍历数组时,使用快指针 i 来检查每个元素。
- 如果当前元素 nums[i] 不等于前一个元素nums[i - 1],则将其复制到慢指针 index 的当前位置,并递增 index。
-
更新数组长度:
- 遍历完成后,index + 1 就是新数组的长度,即不包含值 val 的元素数量。
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;
}
};