自学内容网 自学内容网

Leetcode 238 Product of Array Except Self

https://leetcode.com/problems/product-of-array-except-self/

题意:求数组中每个元素,不包括自己的乘积

思考:对于数组中的每一个数,我可以画成左边数的乘积*右边数的乘积

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int N = nums.size();
        vector<int> ret(N, 1);
        vector<int> left(N, 1);
        vector<int> right(N, 1);
        for(int i = 0; i < N; i++) {
            if( i == 0) {
                left[i] = 1;
            } else {
                left[i] = left[i-1]* nums[i-1];
            }
        }
        for(int i = N-1; i >= 0; i--) {
            if (i == N - 1) {
                right[i] = 1;
            } else {

                right[i] = right[i+1]*nums[i+1];
            }
        }
        for(int i = 0; i < N; i++) {
            ret[i] = left[i] * right[i];
        }  
        return ret;
    }
};

原文地址:https://blog.csdn.net/xxxmmc/article/details/142688399

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!