【发布时间】:2022-01-01 06:03:35
【问题描述】:
LeetCode 问题 26 - 从有序数组中删除重复项
给定一个按非递减顺序排序的整数数组 nums,就地删除重复项,使每个唯一元素只出现一次。元素的相对顺序应该保持不变。
由于在某些语言中无法更改数组的长度,因此您必须将结果放在数组 nums 的第一部分。更正式地说,如果删除重复项后有 k 个元素,则 nums 的前 k 个元素应该保存最终结果。除了前 k 个元素之外,你留下什么都没关系。
将最终结果放入nums的前k个槽后返回k。
不要为另一个数组分配额外的空间。您必须通过使用 O(1) 额外内存就地修改输入数组来做到这一点。
var removeDuplicates = function (nums) {
// Iterating the full array
for (let i = 0; i < nums.length; i++) {
// Checking for the repeating number
if (nums[i] === nums[i + 1]) {
// Removing the element which is repeating
nums = nums.slice(0, i + 1).concat(nums.slice(i + 2));
// Resetting the index after removing the element
i--;
}
}
console.log(nums);
return nums.length;
};
console.log(removeDuplicates([0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3, 4]));
This is the output of the above JS code on Visual Studio Code.
我无法将此代码提交给 LeetCode。预期的输出是编辑后的 nums 数组,而我的输出不匹配。我该如何解决这个问题?
【问题讨论】:
-
您没有按照指示进行操作。他们希望结束数组的大小与起始数组的大小完全相同。你只是应该向下滑动元素。
-
@FrankYellin 在问题陈述中提到,只有数组的前 k 个元素很重要。不分析前 k 个元素之后的元素。
-
说明很清楚,他们不想让你切片。 “你留下什么都没关系”意味着你确实留下了一些东西。我同意他们说得不好。
标签: javascript arrays