LeetCode[1] The sum of two numbers

Some people fall in love, some people drive at night to see the sea, and some people can't solve the first problem of LeetCode.

Not only can I not do the first question, but I can't figure out why.

C code written by myself

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

 I have been making mistakes and can't figure out why. After reading the official code, I set returnSize to 2 first, and then to 0.

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

The main thing is returnSize. I thought it was used to return the result set, but it is actually the size of the returned result. But what I can't figure out is that there is no return, so why can't I not use it.

After checking some blogs, I found that returnSize is used there, and it must be used when calling with main, and you have to give the value yourself, so the problem is solved.

Below is the complete code.

#include<stdio.h>
#include<stdlib.h>

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

int main(){
    int nums[] = {2, 7, 11, 15};
    int numsSize = sizeof(nums)/sizeof(int);
    int target = 9;
    int* returnSize = NULL;
    twoSum(nums, numsSize, target, returnSize);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_40016005/article/details/124131769