此函数返回数字数组中的第一个重复值。
This function returns the first duplicate value in the array of numbers.
我想减少执行时间。我应该做些什么改变?
I want to decrease its execution time. What changes should I do?
有两个重复:数字 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.
推荐答案
如果数组包含数字或字符串,你可以这样做,
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]));