Java Solution of Product of Array Except Self


  • -1
    V

    public class Solution {

    public int[] productExceptSelf(int[] nums) {
    
        int[] ret = new int[nums.length];
       
        
        int overall = 1;
        for(int i = 0; i < nums.length; i++){
            overall = overall * nums[i];
        }
    
        for(int k = 0; k < ret.length; k++){
            ret[k] = 1;
        }
        
        for(int j = 0; j < ret.length; j++){
            if(nums[j] == 0){
                for(int m = 0; m < ret.length; m++){
                    if(m == j){
                        ret[j] = ret[j];
                    }else{
                        ret[j] = ret[j] * nums[m];
                    }
                }
            }else{
                    ret[j] = overall / nums[j];
            }
        }
        
        return ret;
    }
    

    }


  • 0
    S

    ret[j] = overall / nums[j]; you're not supposed to use division, though.


  • 0
    A

    This runs in O(n^2). Question was to have it in O(n)


Log in to reply
 

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