Product of Array Except Self问题及解法
2017-08-25 10:03
531 查看
问题描述:
Given an array of n integers where n > 1,
return an array
equal to the product of all the elements of
Solve it without division and in O(n).
示例
given
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.)
问题分析:
对于第i个元素,我们考虑把前i - 1项的积sum1[i]和后n - i 项的积sum2[i]先算出来,则output[i] = sum1 * sum2.
过程详见代码:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> res = nums;
int sum = res[0];
nums[0] = 1;
for (int i = 1; i < res.size(); i++)
{
nums[i] = sum;
sum *= res[i];
}
sum = 1;
int t;
for (int i = res.size() - 1; i >= 0;i--)
{
t = sum;
sum *= res[i];
res[i] = nums[i] * t;
}
return res;
}
};
Given an array of n integers where n > 1,
nums,
return an array
outputsuch that
output[i]is
equal to the product of all the elements of
numsexcept
nums[i].
Solve it without division and in O(n).
示例
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.)
问题分析:
对于第i个元素,我们考虑把前i - 1项的积sum1[i]和后n - i 项的积sum2[i]先算出来,则output[i] = sum1 * sum2.
过程详见代码:
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
vector<int> res = nums;
int sum = res[0];
nums[0] = 1;
for (int i = 1; i < res.size(); i++)
{
nums[i] = sum;
sum *= res[i];
}
sum = 1;
int t;
for (int i = res.size() - 1; i >= 0;i--)
{
t = sum;
sum *= res[i];
res[i] = nums[i] * t;
}
return res;
}
};
相关文章推荐
- Leetcode之Product of Array Except Self 问题
- Leetcode 238 Product of Array Except Self 时间O(n)和空间O(1)解法
- Leetcode 238 Product of Array Except Self 时间O(n)和空间O(1)解法
- Product of Array Except Self
- Product of Array Except Self
- [LeetCode238]Product of Array Except Self
- [LeetCode] Product of Array Except Self
- 【LeetCode】Product of Array Except Self
- Product of Array Except Self
- Product of Array Except Self
- 【leetcode】Product of Array Except Self
- [LeetCode] Product of Array Except Self
- LeetCode Product of Array Except Self
- leetcode 238: Product of Array Except Self
- LeetCode Product of Array Except Self
- Product of Array Except Self
- leetcode -- Product of Array Except Self -- 重点。常考
- LeetCode 238 Product of Array Except Self(除自身外数组其余数的乘积)
- [LeetCode] Product of Array Except Self
- LeetCode Product of Array Except Self