Simple Java code with math trick


  • 0
    L
    public int[] productExceptSelf(int[] nums) {
            if(nums.length==0) {
                return nums;
            }
            int[] arr = new int[nums.length];
            int start = 1;
            for(int i=nums.length-1;i>=0;i--) {
                arr[i] = start;
                start *= nums[i];
            }
            
            start = nums[0];
            for(int i=1;i<nums.length;i++) {
                arr[i] *= start;
                start *= nums[i];
            }
            
            return arr;        
        }
    

Log in to reply
 

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