我正在尝试解决这个挑战:
此函数接收一组水果(果园),其中除一个之外的所有水果都拼写正确。该函数的任务是识别拼写错误的水果的索引位置。例如,在给定的示例中,函数应返回 0。
['graep', 'grape', 'grape', 'grape']
这是我到目前为止所拥有的:
function findWrongWayFruit(orchard) {
if (orchard.length < 3) {
return 0;
}
const firstFruit = orchard[0];
for (let i = 1; i < orchard.length; i++) {
if (firstFruit !== orchard[i]) {
return i;
}
}
return 0;
}
console.log(findWrongWayFruit(['graep', 'grape', 'grape', 'grape']));
但是,当我尝试运行此代码时,唯一失败的测试用例是:当错误的水果开始时应该返回正确的索引'(AssertionError:预期1等于+0)
当内部
if
条件为真,但 i
为 1 时,仍然有两个选择:返回的索引可以是 0 或 1。要知道哪一个,您应该再进行一次涉及另一个值的比较在数组中(如索引 2 处)。如果该值与 firstFruit
不同,那么您就知道 firstFruit
是偏差值,您应该返回 0。
一个快速的解决方案是将你内心的
return
陈述更改为:
return i == 1 && firstFruit !== orchard[2] ? 0 : i;
function findWrongWayFruit(orchard) {
if (orchard.length < 3) {
return 0;
}
const firstFruit = orchard[0];
for (let i = 1; i < orchard.length; i++) {
if (firstFruit !== orchard[i]) {
return i == 1 && firstFruit !== orchard[2] ? 0 : i;
}
}
return 0;
}
console.log(findWrongWayFruit(['graep', 'grape', 'grape', 'grape']));
function findWrongWayFruit(orchard) {
const tempFruit = orchard[0];
for (let i = 1; i < orchard.length; i++) {
if (tempFruit !== orchard[i] && tempFruit !== orchard[i+1]) {
return i-1;
}
else{
tempFruit = orchard[i]
}
}
return 0;
}
console.log(findWrongWayFruit(['graep', 'grape', 'grape', 'grape']));
您可以根据引用对象中存储的值采用一个数组作为索引,如果已经找到引用,则分配一个错误索引。
如果索引数组中有两个值并且设置了错误索引,则最终返回。
function findWrongWayFruit(orchard) {
if (orchard.length < 3) return;
const
indices = [],
references = {};
let falseIndex;
for (let i = 0; i < orchard.length; i++) {
const value = orchard[i];
if (value in references) falseIndex = references[value];
else references[value] = indices.push(i) - 1;
if (falseIndex !== undefined && indices.length === 2) return indices[1 - falseIndex];
}
return;
}
console.log(findWrongWayFruit(['graep', 'grape', 'grape', 'grape']));
console.log(findWrongWayFruit(['grape', 'graep', 'grape', 'grape']));
console.log(findWrongWayFruit(['grape', 'grape', 'graep', 'grape']));
console.log(findWrongWayFruit(['grape', 'grape', 'grape', 'graep']));
你的逻辑是不正确的,因为你假设第一个水果是正确的,而如果后续的水果拼写不同,那么它们就是错误的。相反,您可以使用 2 种计数,一种用于正确拼写,另一种用于错误拼写。 count==1 将是拼写错误的那个。