C# O(1) space easy to understand


  • 0
    Y
    public class Solution {
        public int[] ProductExceptSelf(int[] nums) {
            int n=nums.Length;
            //pre product
            int[] res=new int[n];
            int prod=1;
            for(int i=0;i<n;i++)
            {
                res[i]=prod;
                prod*=nums[i];
            }
            int afterProd=1;
            //after product
            for(int i=n-1;i>=0;i--)
            {
                res[i]*=afterProd;
                afterProd*=nums[i];
            }
            return res;
        }
    }

Log in to reply
 

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