C# accepted, 496ms, with and without division


  • 2
    R
    public int[] ProductExceptSelf(int[] nums) 
    {
        if (nums == null) return null;
        if (nums.Length == 0) return new int[0];
        if (nums.Length == 1) return new int[] { 0 };
        
        // nums:    1, 2, 3, 4, 5
        // result:  1, 1, 2, 6, 24
        int[] result = new int[nums.Length];
        result[0] = 1;
        for (int i = 1; i < result.Length; i++)
        {
            result[i] = result[i - 1] * nums[i - 1];
        }
        
        int current = nums[nums.Length - 1];
        for (int j = result.Length - 2; j >= 0; j--)
        {
            result[j] = result[j] * current;
            current = current * nums[j];
        }
        return result;
    }
    
    public int[] ProductExceptSelf_WithDivision(int[] nums) {
        
        if (nums == null) return null;
        if (nums.Length == 0) return new int[0];
        if (nums.Length == 1) return new int[] { 0 };
        
        int product = 1;
        int zeroCount = 0;
        int zeroIndex = -1;
        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] != 0)
            {
                product = product * nums[i];
            }
            else
            {
                zeroIndex = i;
                zeroCount++;
            }
        }
        
        if (zeroCount >= 1)
        {
            for (int i = 0; i < nums.Length; i++)
            {
                nums[i] = 0;
            }
            if (zeroCount == 1)
            {
                nums[zeroIndex] = product;
            }
            return nums;
        }
        
        for (int i = 0; i < nums.Length; i++)
        {
            nums[i] = product / nums[i];
        }
        return nums;
    }

Log in to reply
 

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