My java solution without extra space,2ms


  • 0
    S
    public class Solution 
    {
        public int[] productExceptSelf(int[] nums) 
        {
            int last = 0, cur = 0, len = nums.length;
            int[] output = new int[len];
            last = output[len-1] = nums[len-1];
            output[len-1] = 1;
            for(int i=len-2;i>=0;i--)
            {
                cur = nums[i];
                output[i] = output[i+1]*last;
                last = cur;
            }
            last = nums[0]; cur = 0;
            nums[0] = 1;
            for(int i=1;i<len;i++)
            {
                cur = nums[i];
                nums[i] = nums[i-1]*last;
                last = cur;
            }
            for(int i=1;i<len;i++)
            {
                output[i]*=nums[i];
            }
            return output;
        }
    }

Log in to reply
 

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