C++ o(1)space and o(n)time


  • 8
    X
    class Solution {
    public:
        vector<int> productExceptSelf(vector<int>& nums) {
            if(nums.empty()){
                return vector<int>{};
            }
            int n = nums.size();
            vector<int> ans(n, 1);
            int begin = 1, end = 1;
            for(int i = 0;i < n; ++i){
                ans[i] *= begin;
                begin *= nums[i];
                ans[n - 1 - i] *= end;
                end *= nums[n - 1 - i];
            }
            return ans;
        }
    };

  • 0
    C

    thanks for sharing, but isn't this a o(n)-space solution?


  • 0
    T
    This post is deleted!

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.