首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

是否返回数组中第二个不同值的索引?

是的,可以编写一个函数来返回数组中第二个不同值的索引。下面是一个示例的JavaScript代码:

代码语言:txt
复制
function getSecondDistinctIndex(arr) {
  let distinctValues = [];
  
  for (let i = 0; i < arr.length; i++) {
    if (!distinctValues.includes(arr[i])) {
      distinctValues.push(arr[i]);
      
      if (distinctValues.length === 2) {
        return i;
      }
    }
  }
  
  return -1; // 如果数组中没有第二个不同值,则返回-1
}

// 示例用法
const array1 = [1, 2, 2, 3, 4, 4, 5];
const array2 = [1, 1, 1, 1, 2, 2, 3, 3];
const array3 = [1, 2, 3, 4, 5];

console.log(getSecondDistinctIndex(array1)); // 输出: 3
console.log(getSecondDistinctIndex(array2)); // 输出: 4
console.log(getSecondDistinctIndex(array3)); // 输出: -1

这个函数会遍历数组,将遇到的不同值存储在distinctValues数组中。当distinctValues数组的长度达到2时,即找到了第二个不同值,函数会返回该值的索引。如果数组中没有第二个不同值,则返回-1。

这个函数的时间复杂度是O(n),其中n是数组的长度。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券