238. Product of Array Except Self
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { long product = 1, sz = nums.size(); set<int> zero; vector<int> res(sz, 0); for(int i = 0; i < sz; i++) { if(nums[i]) product *= nums[i]; else zero.insert(i); }
if(zero.size() >= 2) return res; else if(zero.size() == 1) { res[*zero.lower_bound(0)] = product; return res; } for(int i = 0; i < sz; i++) { res[i] = product / nums[i]; } return res; } };
|