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

如何计算独眼巨人所需最小镜片配对数?现有代码逻辑存疑

计算独眼巨人所需最小镜片配对数

任务说明

  • 有N个独眼巨人,对应一个包含N个元素的数组
  • 每个元素代表单个独眼巨人的视力值
  • 每个独眼巨人适配的镜片数值为自己的视力值K,同时也能接受K+1或K-1的镜片
  • 独眼巨人总是成对购买镜片(即每对镜片需要满足两个独眼巨人的适配要求)

示例

5个独眼巨人的视力值为[1,-1,2,3,-3],需要购买3对镜片。

我的尝试代码

int cyclops = 4;
int[] cyclopsSightValues = { 1, 7, 4, 1 };
if (cyclops < 2) { return 1;}
List<int> list = cyclopsSightValues.ToList();
int matchCount = 0;

for (int i = 0; i < list.Count; i++)
{
    for (int j = 0; j < list.Count; j++)
    {
        if (list[i] == list[j] ||
            list[i] + 1 == list[j] ||
            list[i] + 2 == list[j] ||
            list[i] - 1 == list[j] ||
            list[i] - 2 == list[j])
        {
            
            int valueToRemove1 = list[i];
            int valueToRemove2 = list[j];
            list.Remove(valueToRemove1);
            list.Remove(valueToRemove2);
            matchCount++;
           
            continue;
        }
    }
}
return matchCount + (cyclops-matchCount*2);

遇到的问题

我原本想通过找到匹配的视力值并从列表移除的方式计算配对数,但结果总是比正确值少1,可能整个逻辑都错了,希望能得到帮助。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:35:14