Java Solution with O(n) complexity


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

Log in to reply
 

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