提前道歉,我知道这可能是一个愚蠢的问题,我错过了一些简单的东西。
在中断了三年之后,我刚刚回到编程领域,为了让自己回到最佳状态,我跳上了Leetcode。作为一种业余爱好,我的经验仅限于写Unity组件等一年左右。
关于二和问题(https://leetcode.com/problems/two-sum/(,我正在使用以下代码(请不要评判我,我想改进,只需要让自己回到其中(:
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] solutionArray = new int[2];
int arrayLength = nums.Length;
for(int i = 0; i < arrayLength; i++){
int testCase = nums[i] + nums[i+1];
if(testCase == target){
solutionArray[0] = i;
solutionArray[1] = i+1;
return solutionArray;
}
}
return null;
}
}
当我";运行代码";,但当我提交时,我收到以下运行时错误:
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
Line 4: Solution.TwoSum(Int32[] nums, Int32 target) in Solution.cs
Line 35: __Driver__.Main(String[] args) in __Driver__.cs
第4行当然是:
int[] solutionArray = new int[2];
我试过在谷歌上搜索答案,但我能找到的大多数问答似乎都是基于有人试图读/写一个不存在的数组索引。
据我所知,我在声明数组后立即收到这个错误,因为即使是第一个测试用例也无法在没有这个运行时错误的情况下完成。
请帮我理解我在这里错过了什么,再次为这样一个愚蠢的问题感到抱歉。
感谢您抽出时间!
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] solutionArray = new int[2];
int arrayLength = nums.Length;
for(int i = 1; i < arrayLength; i++){
int testCase = nums[i] + nums[i-1]; // your line of code was wrong since your trying to access an array member out of its bound.
if(testCase == target){
solutionArray[0] = i-1;
solutionArray[1] = i;
return solutionArray;
}
}
return null;
}
}