Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
You must write an algorithm that runs in O(n) time and without using the division operation.
Example 1:
Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:
Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]
Constraints:
2 <= nums.length <= 105
-30 <= nums[i] <= 30
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.
Follow up:
Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)
1、空间换时间,用数组代替一层for循环。
2、重复利用数组空间,避免额外数组,见注释。
// 我的代码1
class Solution {
public:vector productExceptSelf(vector& nums) {// res[i] = num[0]*...*nums[i-1]* 1 *nums[i+1]*.. *nums[nums.size()-1]vector rights(nums.size());vector results(nums.size());rights[nums.size()-1] = 1;for(int i=nums.size()-1; i>0; i--){rights[i-1] = rights[i] * nums[i];}int left = 1;for(int i=0; i productExceptSelf(vector& nums) {// res[i] = num[0]*...*nums[i-1]* 1 *nums[i+1]*.. *nums[nums.size()-1]//vector rights(nums.size());vector results(nums.size());results[nums.size()-1] = 1; //重复利用results来存放rightsfor(int i=nums.size()-1; i>0; i--){results[i-1] = results[i] * nums[i];}int left = 1;for(int i=0; i
1、问题拆解:左*右;
2、空间换时间;
3、若额外数组的元素都会只用到一次,则可以用省去该额外数组。
上一篇:【数据库实验】完整性约束
下一篇:双软认证办理流程,需要材料