标签:
Question 1: without division. We can simply compose left\right accumulated product arrays:
typedef long long LL; class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { size_t len = nums.size(); vector<LL> left(len), right(len); left[0] = nums[0]; for (int i = 1; i < len - 1; i++) left[i] = nums[i] * left[i - 1]; right[len - 1] = nums.back(); for (int i = len - 2; i > 0; i--) right[i] = nums[i] * right[i + 1]; vector<int> ret(len); for (int i = 0; i < len; i++) { LL l = (!i) ? 1 : left[i - 1]; LL r = (i == len - 1) ? 1 : right[i + 1]; ret[i] = l * r; } return ret; } };
Follow-up question: constant space - we can remove right<int>
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { size_t len = nums.size(); vector<int> ret(len); ret[0] = nums[0]; for (int i = 1; i < len - 1; i++) ret[i] = nums[i] * ret[i - 1]; int right = 1; for (int i = len - 1; i >=0; i --) { ret[i] = (i > 0 ? ret[i - 1] : 1) * right; right *= nums[i]; } return ret; } };
Third solution: sliding window, but may not be quite optimized if there‘s 0
typedef long long LL; class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { size_t len = nums.size(); vector<int> ret(len); int slot = len - 1; LL pro = 1; for (int i = 0; i < len - 1; i++) pro *= nums[i]; for (int i = 0; i < len; i++) // start inx { ret[slot] = pro; if (nums[i]!=0) pro /= nums[i]; else { pro = 1; for (int j = i + 1; j < i + 1 + len - 2; j++) pro *= nums[j % len]; } pro *= nums[slot]; slot = (slot + 1) % len; } return ret; } };
LeetCode "Product of Array Except Self"
标签:
原文地址:http://www.cnblogs.com/tonix/p/4651019.html