0

I'm trying to solve this question:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:
 
 Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because
 nums[0] + nums[1] == 9, we return [0, 1].

my code is:

    /**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
*returnSize = malloc (2 / sizeof(int));
for (int i=0; i<numsSize; i++)
{
    for (int j=0; j< numsSize; j++)
    {
        if (i != j)
        {
           if(nums[i] + nums[j] == target)
           {
               returnSize[0] = i;
               returnSize[1] = j;
           }
        }
    }
}
    return returnSize;
}

as you can see, they added the comment in the beginning of the code to give a hint, but I have no idea how should I use the malloc() function here and for what exact reason. as you can see, I've tried to add the first line with the malloc() function, just from what I have read online and thought this is gonna help, because I thought it's assigning 2 free spaces to the array, which means I'll have plenty of memory and space to insert 2 integers inside of it. But it did not work.

I'll be glad to hear how and for what reason should I use here the malloc function, thanks.

9
  • 3
    You need to multiply, not divide. Commented Jan 12, 2021 at 17:25
  • 2 / sizeof(int) will result in 0, as sizeof(int) is likely to be 4 or 8. As tkausl said, you need to multiply here. Commented Jan 12, 2021 at 17:26
  • ASIDE: You can speed the code up a bit by starting j at i+1 instead of 0. That would also make the i != j test redundant. You can also return the pointer to the array as soon as you have filled it in for the first match of the target value instead of continuing the loops to look for other matches. Commented Jan 12, 2021 at 17:31
  • @IanAbbott Thanks, you are right. I thought that starting j at i+1 would cancel possible matches and that's why I need to run from 0 to cover the whole array. And about your second tip, so are you talking about adding the "return returnArray" inside the second loop so it will return right away the values? Commented Jan 12, 2021 at 17:45
  • Yes, after returnArray[0] = i; returnArray[1] = j;, you can add return returnArray; to return straight away. You still need a return at the end of the function, but that should only be reached if there are no matches. (You could do something to indicate that no match was found, such as setting the array elements to -1 or freeing the memory and returning NULL.) Commented Jan 12, 2021 at 18:02

2 Answers 2

1

It is not allowed to declare local variable that have the same name as an argument at the top of function body. You should give another name.

Also the allocation size is wrong. The size should be (the number of elements) times (the size of one element).

Finally I guess the number of valid elements in the array to return should be written to what is pointed at by returnSize.

Try this:

int* twoSum(int* nums, int numsSize, int target, int* returnSize){
    int *returnArray = malloc (2 * sizeof(int));
    for (int i=0; i<numsSize; i++)
    {
        for (int j=0; j< numsSize; j++)
        {
            if (i != j)
            {
               if(nums[i] + nums[j] == target)
               {
                   returnArray[0] = i;
                   returnArray[1] = j;
               }
            }
        }
    }
    *returnSize = 2;
    return returnArray;
}
Sign up to request clarification or add additional context in comments.

12 Comments

Thanks alot Mike. It works. My questions are: (1) Why do we need to set up *returnSize if we don't even use it? I mean we declare returnArray and we return it. Why do we even need returnSize if we already know the size of the array (which is 2, and that's why we wrote 2 in the malloc function)? What is the contribution of returnSize pointer for us?
(2) Why do we need to use the malloc function if we know the size of the returnArray? I mean we already know, based on the question, that the answer should contain only 2 indexes. So why can't we just declare a new array with 2 arguments inside of it? Something like int array[2]. I know it's not allowed in C but I mean it is kinda stupid don't you think? We literally know the size of the array, and still need to use the malloc function.
(3) Why does the output of the function is [1,0] and not [0,1] based on the following input: nums = [2,7,11,15] & target=9. My first loop runs through (i) which means the first argument in the array which means 2. and (j) runs on the other arguments. which means when i'll find a match (2+7) the "i" will be "0"(because 2 is the first argument in the array) and the "j" will be "1" (because 7 is the second argument in the array). and then I first put i and then j in the returnArray. so it should be [i,j] therefor [0,1] but the output of my code is [1,0]
(1), (2) It should be because the service provider didn't want to create and maintain separate checker for problems expecting fixed-size arrays and use common checker with problems in whcih length of arrays returned as answer varies. Also even if we are working with not onling judge system but stand-alone probram, returning int array[2]; is bad beause it will be invalodated on returning from the function. Returning static int array[2]; may be OK, but be careful when you work with multiple threads or want to maintain results of multiple calls.
(3) Because i = 1, j = 0 is searched later than i = 0, j = 1 and the returning array is overwritten by the answer found later.
|
0

dynamically allocate an array using the malloc, calloc, or realloc functions, the size of the array isn’t stored anywhere in memory. Therefore, there’s no direct way to find the size of a dynamically allocated array. To manage the size of a dynamically allocated array, we must keep track of the size separately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.