用 JavaScript 从数组中返回第一个重复数字
我们需要编写一个函数,它可以返回数组中第一次出现至少两次的元素的索引。如果没有元素出现超过一次,我们需要返回 -1。条件是我们必须在恒定空间中完成此操作(即不使用额外内存)。
让我们为这个问题想出一个解决办法。我们将使用 for 循环来遍历数组,并使用 Array.prototype.lastIndexOf() 方法来检查是否有重复项。
示例
const firstDuplicate = arr => {
for(let i = 0; i < arr.length; i++){
if(arr.lastIndexOf(arr[i]) !== i){
return i;
};
};
return -1;
}
console.log(firstDuplicate([3, 5, 6, 8, 5, 3])); // 0
console.log(firstDuplicate([0, 1, 2, 3, 4, 4, 5])); // 4
console.log(firstDuplicate([0, 1, 1, 2, 3, 4, 4, 5])); // 1
console.log(firstDuplicate([0, 1, 2, 3, 4, 9, 5])); // -1输出
控制台中的输出如下 −
0 4 1 -1
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP