Apologies in advance, I know this is probably a dumb question and I'm missing something simple.
I am just getting back into programming after a 3-year hiatus, and have hopped onto Leetcode to get myself back in the groove. My experience is limited to about a year of writing Unity components etc., as a hobby.
On the Two Sum problem ( https://leetcode.com/problems/two-sum/ ), I am using the following code (please don't judge me, I want to improve just need to get myself back into it):
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;
}
}
The code seems to work when I "run code", but when I submit, I receive the following Runtime Error:
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
Line 4 of course is:
int[] solutionArray = new int[2];
I have tried googling around for the answer, but it seems that most of the Q/A's I can find are based on someone trying to read/write to a non-existent array index.
As far as I understand, I am receiving this error immediately after declaring the array, as not even the first test-case makes it through without this runtime error.
Please help me understand what I am missing here, and again, sorry for such a noob question.
Thank you for your time!