题目:
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].
代码:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int n = nums.size(); vector<int> fromBegin(n); vector<int> fromLast(n); fromBegin[0] = fromLast[0] = 1; for(int i = 1; i < n; ++i) { fromBegin[i] = fromBegin[i-1] * nums[i-1]; fromLast[i] = fromLast[i-1] *nums[n-i]; } vector<int> res(n); for(int i = 0; i < n; ++i) { res[i] = fromBegin[i]*fromLast[n-i-1]; } return res; } };
除自身外乘积算法
本文介绍了一种高效算法,用于解决给定整数数组中,每个元素对应位置的输出等于除自身外所有元素的乘积的问题。此算法不使用除法,并在O(n)的时间复杂度内完成。通过两个辅助数组分别从开始和结束遍历,计算出每个元素左侧和右侧的乘积,最终得到除自身外的乘积。
460

被折叠的 条评论
为什么被折叠?



