my C Solution ordinary idea O(n)


  • 0
    M
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
        int sum = 1;
        int flag = 0;
        for (int i = 0; i < numsSize && flag < 2; i++){
            if (!nums[i]) {flag++; continue;}
            sum = sum * nums[i];
        }
        int* result = (int*)malloc(sizeof(int) * numsSize);
        memset(result, 0, sizeof(int)*numsSize);
        *returnSize = numsSize;
        if (flag>1) return result;
        for (int i = 0; i < numsSize; i++){
            if (!nums[i]) {result[i] = sum; continue;}
            if (flag > 0) {result[i] = 0; continue;}
            result[i] = sum / nums[i];
        }
        return result;
    }
    

Log in to reply
 

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