Alex Larose

Generation

code to explanationSat, 04 Mar 2023

int* twoSum(int* nums, int numsSize, int target, int* returnSize){ int i, j; int *result = (int*)malloc(2*sizeof(int)); for(i=0; i<numsSize; i++){ for(j=i+1; j<numsSize; j++){ if(nums[i] + nums[j] == target){ result[0] = i; result[1] = j; *returnSize = 2; return result; } } } return NULL; }

The function twoSum takes four arguments: array of integers, size of the array, target integer and pointer to size of array which will be returned. The function returns pointer to the array of two elements namely indices of the target number. First we declare pointer to the array of two elements, allocate memory for this array and set pointer to the array of two elements equal to the result. Then we loop through the array and check if the sum of the two elements is equal to the target. If yes, we return the array of two elements that stores the indices of the target number. If not, we return null.

Questions about programming?Chat with your personal AI assistant