Supposedly bad test case in C:


  • 0

    @xidui @1337c0d3r. I believe the "C" test case for this solution is bad. The find() API returns either a true or false, however the output in this test case is empty i.e [].

    OJ's Wrong Answer Output:

    Input:    [find(0)]
    Output:   []
    Expected: [false]
    

    Solution:

    struct TwoSum {
        int *nums, numsSize;
    };
    
    /** Initialize your data structure here. */
    struct TwoSum* twoSumCreate() {
        struct TwoSum *twoSum = malloc(sizeof(struct TwoSum));
        twoSum->nums = NULL;
        twoSum->numsSize = 0;
        return twoSum;
    }
    
    int cmpFunc(const void *a, const void *b) { return *(int *)a - *(int *)b; }
    
    /** Add the number to an internal data structure. */
    void add(struct TwoSum* twoSum, int number) {
        twoSum->nums = realloc(twoSum->nums, ++(twoSum->numsSize) * sizeof(int));
        twoSum->nums[twoSum->numsSize - 1] = number;
        qsort(twoSum->nums, twoSum->numsSize, sizeof(int), cmpFunc);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    bool find(struct TwoSum* twoSum, int value) {
        if (twoSum->nums == NULL) return false;
        int lo = 0, hi = twoSum->numsSize - 1;
        while (lo < hi) {
            int sum = twoSum->nums[lo] + twoSum->nums[hi];
            if (sum < value) {
                lo++;
            } else if (sum > value) {
                hi--;
            } else {
                return true;
            }
        }
        return false;
    }
    
    /** Deallocates memory previously allocated for the data structure. */
    void twoSumFree(struct TwoSum* twoSum) {
        if (twoSum->nums) free(twoSum->nums);
        free(twoSum);
    }
    

Log in to reply
 

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