关于TwoSum方法未找到符合条件元素时返回值的技术问询
解决TwoSum方法的编译错误与无匹配时的返回值问题
错误原因
你的代码仅在找到符合条件的元素对时返回值,当遍历完所有元素仍未找到匹配项时,没有对应的返回路径,这就是C#编译器报错的原因。
无匹配时的常见处理方案
1. 返回空数组new int[0]
这是最常用的安全处理方式,调用方可以通过判断数组长度是否为0来处理无匹配的场景:
public int[] TwoSum(int[] nums, int target) { for (int x = 0; x < nums.Length; x++) { for (int y = x + 1; y < nums.Length; y++) { if (nums[x] + nums[y] == target) { return new int[] { x, y }; } } } // 无匹配时返回空数组 return new int[0]; }
2. 抛出异常
如果业务逻辑中必须存在符合条件的元素对,找不到匹配属于异常情况,可以抛出明确的异常告知调用方:
public int[] TwoSum(int[] nums, int target) { for (int x = 0; x < nums.Length; x++) { for (int y = x + 1; y < nums.Length; y++) { if (nums[x] + nums[y] == target) { return new int[] { x, y }; } } } // 无匹配时抛出异常 throw new InvalidOperationException("未找到和为目标值的两个元素"); }
3. 返回null
这种方式需要调用方额外处理空引用,容易引发NullReferenceException,一般不推荐使用:
public int[] TwoSum(int[] nums, int target) { for (int x = 0; x < nums.Length; x++) { for (int y = x + 1; y < nums.Length; y++) { if (nums[x] + nums[y] == target) { return new int[] { x, y }; } } } // 无匹配时返回null return null; }
选择建议
- 若业务允许无匹配的情况存在,优先返回空数组,调用方处理更安全。
- 若业务规则强制要求必须存在匹配项,抛出异常更合理,能及时暴露不符合预期的场景。
内容的提问来源于stack exchange,提问作者Denis
相关产品推荐
相关产品推荐

