当前位置:   article > 正文

【Leet Code】238. Product of Array Except Self---Medium_leetcode238

leetcode238

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.)

思路:

此题目有一个很简单的解法:将所有的元素相乘得到值total,然后对结果数组求值的时候只需要用total除以原数组中对应的元素,但是题目规定不允许用除法,所以需要另寻他法。

两次遍历数组,第一次将前面相乘的结果存入结果数组中,然后第二次再将后面相乘的值与前面相乘的结果相乘并存入最终的结果数组中。

代码实现:

  1. class Solution {
  2. public:
  3. vector<int> productExceptSelf(vector<int>& nums) {
  4. vector<int> res(nums.size(), 1);
  5. for(int i = 1; i < nums.size(); ++i)
  6. res[i] = res[i-1] * nums[i-1];
  7. int temp = nums.back();
  8. for(int i = nums.size()-2; i >= 0; --i)
  9. {
  10. res[i] = res[i] * temp;
  11. temp *= nums[i];
  12. }
  13. return res;
  14. }
  15. };


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/818347
推荐阅读
相关标签
  

闽ICP备14008679号