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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…