Finding target sum of two numbers in array

Below code will work and produce expected results.

As other comments say, you should learn concept of pointer and memory management in C/C++. There is nothing similar can be find in another languages (Java, C# and other), so it will be new concept for you.

void twoSum(int *nums, int size,  int numsSize, int target, int * res)
{
    for (int i = 0; i < size; i++)
    {
        for (int j = i + 1; j < size; j++)
        {
            if (nums[j] == target - nums[i])
            {
                res[0] = i;
                res[1] = j;
                return;
            }
        }
    }
}

int main()
{
    int array[5] = { 1, 2, 3, 4, 5 };
    int results[2];
    twoSum(array, sizeof(array)/sizeof(array[0]), 5, 3, results);

    return 0;
}

Leave a Comment