I’m new to programming in C and wanted to try some LeetCode problems to get used to the language. Problem: I failed at the first task.
The task is to find matching pairs in an array which match up to the target parameter.
int* twoSum(int* nums, int numsSize, int target, int* returnSize) {
int length = sizeof(nums) / sizeof(nums[0]);
int i, ii;
int *Paar = (int*)malloc(2*sizeof(int));
for(i=0; i<length; i++) {
for(ii=0; ii<length; ii++) {
if(i != ii) {
if(nums[i] + nums[ii] == target) {
Paar[0] = i;
Paar[1] = ii;
*returnSize = 2;
return Paar;
}
}
}
}
return Paar;
}
my approach was to just brute force the task.
Testcases:
For the input [2,7,11,15]
and target 9
it works.
For the input [3,3]
and target 6
it works.
For the input [3,2,4]
and target 6
it does not work. There it uses the return at the end, which is just a placeholder.
I can imagine that the order of the elements could be the reason but I don’t know why this should be a problem since I’m checking every possibility.
ANEXL is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
6
Solved. I should’ve used the given parameter numsSize for the loops. Now it works. Thanks to @John3136
ANEXL is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.