- 48.0%
https://leetcode.com/problems/product-of-array-except-self/#/description
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).
1 | For example, 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.)
剑指offer 52
https://discuss.leetcode.com/topic/20434/o-n-time-and-o-1-space-c-solution-with-explanation
O(n) time and O(1) space C++ solution with explanation
方法一:
First, consider O(n) time and O(n) space solution.
1 | class Solution { |
方法二:
空间从o(n)降低到o(1)
对从前至后的部分考虑保留前一个值,得到结果。
很巧妙地方法,节省了空间。
We just need to change the two vectors to two integers and note that we should do multiplying operations for two related elements of the results vector in each loop.
1 | class Solution { |
https://discuss.leetcode.com/topic/37927/how-from-o-n-to-o-1
How from O(N) to O(1)
Here is the O(N) based C++ implementation
1 | class Solution { |
How to use O(1) ?
By observing the above code, we can just for every position multiply it to its right position.
Just the idea to think reversly !
1 | class Solution { |
https://discuss.leetcode.com/topic/18877/my-c-solution-o-n-time-with-no-extra-space
My C++ solution, O(n) time with no extra space
1 | vector<int> productExceptSelf(vector<int>& nums) { |
https://discuss.leetcode.com/topic/18983/python-solution-accepted-o-n-time-o-1-space
Python solution (Accepted), O(n) time, O(1) space
1 | class Solution: |
https://discuss.leetcode.com/topic/30115/very-easy-two-passes-solution
Very easy two passes solution
1 | // two passes, O(2n) |