You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

findWrongWayFruit函数首元素为反向水果时测试失败求助

问题:反向水果索引判断函数无法处理首元素为反向的情况

题目要求

实现findWrongWayFruit函数,接收一个水果数组(orchard),数组中除1个水果为反向拼写外,其余均为同一正向拼写的水果。函数需返回该反向水果的索引。注意:若数组长度小于3,无法判断哪个是反向,返回0。示例如下:

findWrongWayFruit(['apple', 'apple', 'elppa']) // 返回2
findWrongWayFruit(['apple', 'elppa', 'apple']) // 返回1
findWrongWayFruit(['banana', 'ananab', 'banana', 'banana']) // 返回1
findWrongWayFruit(['apple', 'elppa']) // 返回0

我的实现代码

function findWrongWayFruit(orchard) {
  const firstFruit = orchard[0];
  if (orchard.length < 3) {
    return 0; // Return 0 if the orchard length is less than 3
  }
  
  for (let i = 1; i < orchard.length; i++) {
    if (firstFruit !== orchard[i]) {
      return i; // Return the index of the wrong-way fruit
    }
  }
}

测试结果

6项通过,1项失败:

  • should be a function:✓ Well done!
  • should return a number:✓ Well done!
  • should return 0 when passed an array length smaller than 3:✓ Well done!
  • should return the correct index when the wrong-way fruit is in the middle of the array:✓ Well done!
  • should return the correct index when the wrong-way fruit is at start:✕ AssertionError: expected 1 to equal +0
  • should return the correct index when the wrong-way fruit is at the end:✓ Well done!
  • should return the correct index when the wrong-way fruit is at any other random position:✓ Well done!

问题根源

当前逻辑默认第一个元素是正确的,只要遇到和第一个元素不同的就返回当前索引。但如果第一个元素才是反向的,后续所有元素都是正确的,函数会直接返回索引1,而正确结果应该是0。

修正思路与代码

思路1:统计出现次数

因为数组中只有一个反向水果,正确水果的出现次数是数组长度-1,反向水果仅出现1次。通过统计每个水果的出现次数,找到出现次数为1的水果,再返回其索引。

修正后代码:

function findWrongWayFruit(orchard) {
  if (orchard.length < 3) {
    return 0;
  }
  
  // 统计每个水果的出现次数
  const fruitCount = {};
  orchard.forEach(fruit => {
    fruitCount[fruit] = (fruitCount[fruit] || 0) + 1;
  });
  
  // 找到仅出现1次的反向水果
  const wrongFruit = Object.keys(fruitCount).find(fruit => fruitCount[fruit] === 1);
  
  // 返回该水果的索引
  return orchard.indexOf(wrongFruit);
}

思路2:通过前三个元素确定正确水果

利用"大部分水果是正确的"这个前提,前三个元素中必然能确定正确的水果:

  • 如果前两个元素相同,正确水果就是它;
  • 如果第一个和第三个相同,正确水果是第一个;
  • 如果后两个相同,说明第一个是反向的,直接返回0。
    之后遍历数组找到与正确水果不同的元素索引即可。

修正后代码:

function findWrongWayFruit(orchard) {
  if (orchard.length < 3) {
    return 0;
  }
  
  let correctFruit;
  // 从三个元素中确定正确水果
  if (orchard[0] === orchard[1]) {
    correctFruit = orchard[0];
  } else if (orchard[0] === orchard[2]) {
    correctFruit = orchard[0];
  } else {
    // 后两个相同,第一个是反向的
    return 0;
  }
  
  // 遍历找到反向水果的索引
  for (let i = 0; i < orchard.length; i++) {
    if (orchard[i] !== correctFruit) {
      return i;
    }
  }
  
  // 题目保证有一个反向水果,此处为兜底返回
  return 0;
}

内容的提问来源于stack exchange,提问作者Room4Renzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 06:22:47