LeetCode //238. Product of Array Except Self

238. Product of Array Except Self

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

 

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Constraints:

  • 2 < = n u m s . l e n g t h < = 1 0 5 2 <= nums.length <= 10^5 2<=nums.length<=105
  • -30 <= nums[i] <= 30
  • The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

From: LeetCode
Link: 238. Product of Array Except Self


Solution:

Ideas:
This function will return an array where each element at index i is the product of all elements in the input array except the element at index i. It first calculates the cumulative product from the left (excluding the current element), and then multiplies this with the cumulative product from the right (again excluding the current element).
The result array is allocated on the heap using malloc, so the caller of this function should be responsible for freeing the memory. The size of the output array is stored in the location pointed to by returnSize.
Code:
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* productExceptSelf(int* nums, int numsSize, int* returnSize){
    int* result = (int*)malloc(numsSize * sizeof(int));
    *returnSize = numsSize;
    
    // First pass: from left to right
    int left_product = 1;
    for (int i = 0; i < numsSize; i++) {
        result[i] = left_product;
        left_product *= nums[i];
    }
    
    // Second pass: from right to left
    int right_product = 1;
    for (int i = numsSize - 1; i >= 0; i--) {
        result[i] *= right_product;
        right_product *= nums[i];
    }
    
    return result;
}

你可能感兴趣的:(LeetCode,leetcode,算法,c语言)