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

238. [LeetCode] Product of Array Except Self

时间:2019-02-26 17:37:04      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:where   ret   temp   namespace   space   nts   ace   const   一个   

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

 


 

 

 

 

注释:用两个指针,前面的指针fromBegin比返回的res少乘一个当前的i,后面的指针也是如此。当i到达结尾时,前后都覆盖到了。



#include <cstdio> #include <vector> #include<iostream> using namespace std; class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n=nums.size(); int fromBegin=1; int fromLast=1; vector<int> res(n,1); for(int i=0;i<n;i++){ res[i]*=fromBegin; fromBegin*=nums[i]; res[n-1-i]*=fromLast; fromLast*=nums[n-1-i]; } return res; } }; int main(){ vector<int> temp; temp.push_back(2); temp.push_back(2); temp.push_back(2); temp.push_back(2); temp.push_back(2); temp.push_back(2); temp.push_back(2); temp.push_back(2); Solution test; test.productExceptSelf(temp); return 0; }

 

238. [LeetCode] Product of Array Except Self

标签:where   ret   temp   namespace   space   nts   ace   const   一个   

原文地址:https://www.cnblogs.com/250101249-sxy/p/10438014.html

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