减少“firstDuplicate”的执行时间。算法

编程入门 行业动态 更新时间:2024-10-15 12:38:03
本文介绍了减少“firstDuplicate”的执行时间。算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 function firstDuplicate(a) { var numbers = {}, res; foo: for (var i = 0; i < a.length; i++) { for (var j = i + 1; j < a.length; j++) { if (a[i] === a[j]) { numbers[a[i]] = j - i; if (j - i === 1 ) { break foo; } } } } var keys = Object.keys(numbers), res = keys[0]; keys.forEach(function (v) { res = numbers[res] > numbers[v] ? v : res; }); console.log(res); return res === undefined ? -1 : Number(res); }

此函数返回数字数组中的第一个重复值。

This function returns the first duplicate value in the array of numbers.

我想减少执行时间。我应该做些什么改变?

I want to decrease its execution time. What changes should I do?

  • 对于 a = [2,3,3,1,5,2] ,输出应为 firstDuplicate(a)= 3 。
  • For a = [2, 3, 3, 1, 5, 2], the output should be firstDuplicate(a) = 3.
  • 有两个重复:数字 2 和 3 。第二次出现 3 的索引小于第二次出现的 2 ,所以答案是 3 。

    There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than the second occurrence of 2 does, so the answer is 3.

  • 对于 a = [2 ,4,3,5,1] ,输出应为 firstDuplicate(a)= -1 。
  • For a = [2, 4, 3, 5, 1], the output should be firstDuplicate(a) = -1.
  • 推荐答案

    如果数组包含数字或字符串,你可以这样做,

    If the array contains number or string you can do something like this,

    //Returns the first duplicate element function firstDup(arr) { let o = {}; //an empty object for (let i = 0; i < arr.length; i++) { if (o[arr[i]]) { //check if the property exists return arr[i]; } else { o[arr[i]] = 'a'; //set the object's property to something non falsy } } return -1; //If No duplicate found return -1 } console.log(firstDup([2, 3, 3, 1, 5, 2])); console.log(firstDup([2, 4, 3, 5, 1]));

    更多推荐

    减少“firstDuplicate”的执行时间。算法

    本文发布于:2023-11-30 16:13:33,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1650645.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:执行时间   算法   firstDuplicate

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!