zoukankan      html  css  js  c++  java
  • 238. Product of Array Except Self(对O(n)和递归又有了新的理解)

    238. Product of Array Except Self

     
     
    Total Accepted: 41565 Total Submissions: 97898 Difficulty: Medium

    Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

    Solve it without division and in O(n).

    For example, given [1,2,3,4], return [24,12,8,6].

    Follow up:
    Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

    Subscribe to see which companies asked this question

    Code:


    int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
        int i,tmp = 1;
        int *arr = (int *)malloc(sizeof(int)*(numsSize));
     
        arr[numsSize-1] = 1;
        for(i = numsSize-2;i>=0;i--)
            arr[i] = arr[i+1]*nums[i+1];
        for(i = 0;i<numsSize;i++)
        {
            arr[i] = tmp*arr[i];
            tmp*=nums[i];
        }
        *returnSize = numsSize;
        return arr;
    }

    //一个嵌套把前边的乘积之和带过来,再在跳出嵌套之前得出相应的结果。

    int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
            multiply(nums, 1, 0, numsSize);
            *returnSize = numsSize;
            return nums;
        }

        int multiply(int *a, int fwdProduct, int indx, int N) {
            int revProduct = 1;
            if (indx < N) {
                revProduct = multiply(a, fwdProduct * a[indx], indx + 1, N);
                int cur = a[indx];
                a[indx] = fwdProduct * revProduct;
                revProduct *= cur;
            }
            return revProduct;
        }

  • 相关阅读:
    Spring Security配置logout地址
    flex布局
    视口的学习笔记
    box-sizing属性
    css清除浮动
    line-height的理解
    position和float小结
    css居中方法小结
    margin重叠
    浅谈负margin
  • 原文地址:https://www.cnblogs.com/Alex0111/p/5386009.html
Copyright © 2011-2022 走看看