gpt4 book ai didi

javascript - 从排序数组中删除重复项 - 使用 Set (ES6)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:35 25 4
gpt4 key购买 nike

我正在用 JS 写 Leetcode,

第26题(有序数组去除重复项)

我正在尝试使用 Set (ES6),但它无法在 Leetcode 页面上运行(用于直接提交),但它可以在控制台中运行。

此外,我还发现旧的答案已经列出了 Set as a solution。这是 old post !

作者在旧帖中说:

ES6 provides the Set object, which makes things a whole lot easier

// code from the old post

function uniq(a) {
return Array.from(new Set(a));
}
or

let uniq = a => [...new Set(a)];

这是我的 Set 代码:

//this is my code with Set

var removeDuplicates = function(nums) {
let set = new Set(nums);
let setArr = [...set];
return setArr;
};


下面是代码在 Leetcode 页面上运行后显示的内容,输出与预期的不同:

On Leetcode Page

这是网页控制台上的显示
Console

谁能帮我理解背后的原因是什么?或者我只是误解了这个问题?谢谢!

最佳答案

你的函数完美地从数组中删除了重复项,但它没有完成 leetcode 任务 asks for 的任务:

Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

另外,预期的返回是一个数字,而不是一个数组。它声明您需要返回新数组的长度(唯一元素的数量)。

关于javascript - 从排序数组中删除重复项 - 使用 Set (ES6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57171445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com