Last executed input:[], what's wrong with my code?


  • 0
    L

    I found that in the struct NumArray, if I swap those two statements,
    my code would be accepted,
    but I wonder why the 'int *sum' can not be written in first line.
    thanks

    struct NumArray {
        int *sum;
        int size;
    
    };
    

    /** Initialize your data structure here. */

    struct NumArray* NumArrayCreate(int* nums, int numsSize) {
        struct NumArray *array;
        array=(struct NumArray*)malloc(sizeof(struct NumArray));
        array->sum=(int *)calloc(numsSize+1,sizeof(int));
        array->size=numsSize;
        array->sum[0]=0;
    
        for(int i=0;i<numsSize;i++){
            array->sum[i+1]=array->sum[i]+nums[i];
        }
        return array;
    }
    
    int sumRange(struct NumArray* numArray, int i, int j) {
        int sum = 0;
        if(!numArray) return 0;
        sum=numArray->sum[j+1]-numArray->sum[i];
        return sum;
    }
    

    /** Deallocates memory previously allocated for the data structure. */

    void NumArrayFree(struct NumArray* numArray) {
        free(numArray);
        free(numArray->sum);
    }

  • 0
    S

    The deallocation process looks suspicious: I don't think freeing a member of a struct after the whole struct is freed is a good idea.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.