码迷,mamicode.com
首页 > 其他好文 > 详细

238. Product of Array Except Self

时间:2018-04-11 15:04:19      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:size   完成   保存   cte   ext   tput   span   put   ace   

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

 

解题思路:

套头多要求无法使用除法,还要在O(n)中完成。

可以将每一个从前到后和从后到前的乘数保存下来,例如ret[8]就是0-6的相乘和8-n-1的相乘的相乘。

这里还要是否考虑乘数可能溢出,是否要使用大数的问题,这里先用int试试

  1. class Solution {  
  2. public:  
  3.     vector<int> productExceptSelf(vector<int>& nums) {  
  4.   
  5.         int n = nums.size();  
  6.         vector<int> ret(n,1);  
  7.           
  8.         int from_start=1;  
  9.         int from_end=1;  
  10.           
  11.         for(int i=0;i<n;i++){  
  12.             ret[i]*=from_start;  
  13.             from_start*=nums[i];  
  14.             ret[n-i-1]*=from_end;  
  15.             from_end*=nums[n-i-1];     
  16.         }  
  17.         return ret;  
  18.           
  19.     }  
  20. };  

238. Product of Array Except Self

标签:size   完成   保存   cte   ext   tput   span   put   ace   

原文地址:https://www.cnblogs.com/liangyc/p/8794434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!