026 移除有序数组中的重复项
2025年2月25日大约 2 分钟
🔗 相关链接
📜 题目描述
给定一个 非严格递增排列 的数组 nums
,需要 原地 删除重复出现的元素,使每个元素只出现一次,返回删除后数组的新长度。元素的相对顺序应该保持一致。然后返回 nums
中唯一元素的个数。
考虑 nums
的唯一元素的数量为 k
,需要执行以下操作:
- 更改数组
nums
,使nums
的前k
个元素包含唯一元素,并按照它们最初在nums
中出现的顺序排列。 nums
的其余元素与nums
的大小不重要。- 返回
k
。
🧪 判题标准
系统会用下面的代码来测试题解:
int[] nums = [...]; // 输入数组
int[] expectedNums = [...]; // 长度正确的期望答案
int k = removeDuplicates(nums); // 调用
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
如果所有的断言都通过,那么题解将会通过。
📊 示例
示例 1
输入:
nums = [1,1,2]
输出:
2, nums = [1,2,_]
解释:
函数应返回新的长度 2
,并且原数组 nums
的前两个元素被修改为 1, 2
。不需要考虑数组中超出新长度后面的元素。
示例 2
输入:
nums = [0,0,1,1,1,2,2,3,3,4]
输出:
5, nums = [0,1,2,3,4]
解释:
函数应返回新的长度 5
,并且原数组 nums
的前五个元素被修改为 0, 1, 2, 3, 4
。不需要考虑数组中超出新长度后面的元素。
📝 提示
1 <= nums.length <= 3 * 10^4
-10^4 <= nums[i] <= 10^4
nums
已按 非严格递增 排列
💡 思路
相较于027 移除元素,该题需要删除有序数组中的重复项,即要删除的元素是动态的,我们可以开辟一个数组,记录某值在之前的记录中是否出现过。其他的思路仍然像027 移除元素一样。
💻 代码实现
public int removeDuplicates(int[] nums) {
if (nums.length == 1) {
return 1;
}
boolean[] flag = new boolean[20001];
int scanIndex = 0;
int currentIndex = 0;
int length = 0;
while (scanIndex < nums.length) {
if (!flag[nums[scanIndex] + 10000]) {
nums[currentIndex] = nums[scanIndex];
flag[nums[scanIndex] + 10000] = true;
length++;
currentIndex++;
}
scanIndex++;
}
return length;
}