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

标签 javascript algorithm set

我正在用 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/

相关文章:

JavaScript:条件(三元)与非 bool 值的 bool 值或?

java - 将包含列表的实例映射到 flatMap(使用流)

Java 8 : mapping list inisde a list

javascript - 不带括号调用JS函数

javascript - CSS/JS : Floating block elements of differing heights?

javascript - firefox 从本地 JS 文件读取网页——访问受限 URI 被拒绝,代码 : 1012, nsresult: NS_ERROR_DOM_BAD_URI

algorithm - 要在未加权图上实现 Dijkstra 最短路径算法使其在线性时间内运行,应该使用哪种数据结构?

c++ - 给定不同长度的序列,找到每个序列共有的最大数字序列

algorithm - 为什么二叉搜索树的中序遍历保证非降序?

set - OpenEdge 10.2A - INPUT THROUGH 设置在 Windows 10 上的 Windows Update 1703 后不起作用