如何计算独眼巨人所需最小镜片配对数?现有代码逻辑存疑
计算独眼巨人所需最小镜片配对数
任务说明
- 有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
相关产品推荐
相关产品推荐

