查找数组中的第一个冗余元素——JavaScript
假设需要编写一个函数,该函数返回在数组中至少出现过两次的第一个元素的索引。如果没有任何元素出现超过一次,则返回 -1。我们必须在常量空间(即不使用额外的内存)中做到这一点。
那么,让我们为此问题编写解决方案。我们将使用一个 for 循环来迭代数组,并使用 Array.prototype.lastIndexOf() 方法来检查重复项。
示例
代码如下
const arr1 = [0, 1, 1, 2, 3, 4, 4, 5];
const firstRedundant = arr => {
for(let i = 0; i < arr.length; i++){
if(arr.lastIndexOf(arr[i]) !== i){
return i;
};
};
return -1;
}
console.log(firstRedundant(arr1)); // 1输出
这将在控制台中生成以下输出
1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP