我正在尝试解决寻找在数组中出现奇数次的数字的练习。到目前为止,我已经得到了这个结果,但是输出结果是一个出现了偶数次的整数。例如,数字2出现3次,数字4出现6次,但输出是4,因为它将其视为出现5次。它怎么会返回它发现为奇数的第一个集合呢?如有任何帮助,我们将不胜感激!
function oddInt(array) {
var count = 0;
var element = 0;
for(var i = 0; i < array.length; i++) {
var tempInt = array[i];
var tempCount = 0;
for(var j = 0; j count) {
count = tempCount;
element = array[j];
}
}
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);发布于 2017-04-18 06:32:43
这是因为您正在设置element变量,所以当它找到1、3和5时,就会设置它4。
让我们一步一步地检查代码:
function oddInt(array) {
// Set the variables. The count and the element, that is going to be the output
var count = 0;
var element = 0;
// Start looking the array
for(var i = 0; i < array.length; i++) {
// Get the number to look for and restart the tempCount variable
var tempInt = array[i];
var tempCount = 0;
console.log("");
console.log(" * Looking for number", tempInt);
// Start looking the array again for the number to look for
for(var j = 0; j count) {
console.log("Odd count found:", tempCount);
count = tempCount;
element = array[j];
}
}
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);我们要做的是在循环所有数组后检查计数,用这种方式:
function oddInt(array) {
// Set the variables. The count and the element, that is going to be the output
var count = 0;
var element = 0;
// Start looking the array
for(var i = 0; i < array.length; i++) {
// Get the number to look for and restart the tempCount variable
var tempInt = array[i];
var tempCount = 0;
console.log("");
console.log(" * Looking for number", tempInt);
// Start looking the array again for the number to look for
for(var j = 0; j count) {
console.log("Odd count found:", tempCount);
count = tempCount;
element = tempInt;
}
}
return element;
}
oddInt([1,2,2,2,4,4,4,4,4,4,5,5]);顺便说一句,这只是为了让您了解问题出在哪里并从中学习,尽管这不是最优化的方法,因为您可能会注意到您正在寻找,比方说,数字2三次,当你第一次得到你想要的输出时。如果性能是家庭作业的一部分,那么你应该换一种方式思考:P
https://stackoverflow.com/questions/43460509
复制相似问题