JavaScript查找数组中的第一个冗余元素方法详解

2023年11月23日09:55:58

假设,我们需要编写一个函数,该函数返回数组中至少出现两次的第一个元素的索引。如果没有元素出现多次,我们必须返回-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

  • 更新时间:2023年11月23日09:55:58 ,共 419 字。