2 ms Java solution with 2 loops


  • -1
    E

    public class Solution {
    public int[] productExceptSelf(int[] nums) {
    //create new product array of the same length
    int res[]=new int[nums.length];
    int prod=1,zflag=0;
    //get product of all the numbers just be careful that 0 is not included in the product
    for(int i=0;i<nums.length;i++){
    if(nums[i]!=0){
    prod=prod*nums[i];
    }
    else{
    zflag++;
    }
    }
    for(int j=0;j<nums.length;j++){
    //if no zero exists in the array then array entry is product/corresponding array entry
    if(zflag==0){
    res[j]=prod/nums[j];
    }
    //if only one zero exits then all the entries except the zeroth position entry are zero
    else if(zflag==1 && nums[j]==0){
    res[j]=prod;
    }
    //for more than 2 zeros or with one zero the other entries would be zero
    else{
    res[j]=0;
    }
    }
    return res;
    }
    }


  • 1
    S

    "Solve it without division and in O(n)."

    res[j]=prod/nums[j];
    

Log in to reply
 

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