问题
我不确定我在这里做错了什么。我正在做一个coding challenge on CodeFights使用普通 JavaScript 查找并返回数组中的第一个重复元素。我的代码适用于 2 个测试数组(a
和 c
),但不适用于没有重复元素的情况。
我的代码
console.clear();
var a = [2, 1, 3, 5, 3, 2];
var b = [2, 4, 3, 5, 1];
var c = ["apple", "orange", "grape", "orange", "grape"];
// create an object to store the counts
var counts = {};
function firstDuplicate(arr) {
// loop through passed array of numbers
for (var i=0; i<a.length; i++) {
var num = arr[i];
if (counts[num] === undefined) {
counts[num] = 1;
} else if (counts[num] == 1) {
++counts[num];
return num;
}
}
return -1;
}
console.log(firstDuplicate(a)); // 3
console.log(firstDuplicate(b)); // -1
console.log(firstDuplicate(c)); // orange
我的问题
我知道我的代码大部分是正确的,那么我缺少什么/或者我放错了什么地方?如何让“null”大小写起作用(当没有重复字符时)。
最佳答案
您希望每次调用 firstDuplicate
时重置counts
。否则每次调用都会共享同一个对象。
您还在 for
循环中引用 a
,但应该引用 arr
函数参数。
var a = [2, 1, 3, 5, 3, 2];
var b = [2, 4, 3, 5, 1];
var c = ["apple", "orange", "grape", "orange", "grape"];
function firstDuplicate(arr) {
// move this definition inside the function so that each
// time you call firstDuplicate() you get a new counts object.
var counts = {};
// use arr.length so that you are iterating through the arr parameter
for (var i=0; i<arr.length; i++) {
var num = arr[i];
if (counts[num] === undefined) {
counts[num] = 1;
} else if (counts[num] == 1) {
++counts[num];
return num;
}
}
return -1;
}
console.log(firstDuplicate(a)); // 3
console.log(firstDuplicate(b)); // -1
console.log(firstDuplicate(c)); // orange
关于JavaScript 编码面试数组中的第一个重复字符不适用于 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50711835/