美文网首页
238. Product of Array Except Sel

238. Product of Array Except Sel

作者: xingzai | 来源:发表于2019-05-13 21:25 被阅读0次

题目链接
tag:

  • Medium;

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

Example:

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

Note: Please solve it without division and in O(n).

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

思路:
  本题给我们一个数组,让我们返回一个新数组,对于每一个位置上的数是其他位置上数的乘积,并且限定了时间复杂度O(n),并且不让用除法。如果让用除法的话,那这道题Easy,因为可以先遍历一遍数组求出所有数字之积,然后除以对应位置的上的数字。但是这道题禁止使用除法。我们想,对于某一个数字,如果我们知道其前面所有数字的乘积,同时也知道后面所有的数乘积,那么二者相乘就是我们要的结果,所以我们只要分别创建出这两个数组即可,分别从数组的两个方向遍历就可以分别创建出乘积累积数组。代码如下:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> fd(n, 1), bd(n, 1), res(n);
        for (int i=0; i<n-1; ++i) {
            fd[i+1] = fd[i] * nums[i];
        }
        for (int i=n-1; i>0; --i) {
            bd[i-1] = bd[i] * nums[i];
        }
        for (int i = 0; i < n; ++i) {
            res[i] = fd[i] * bd[i];
        }
        return res;
    }
};

相关文章

网友评论

      本文标题:238. Product of Array Except Sel

      本文链接:https://www.haomeiwen.com/subject/hzkdaqtx.html