Algorithm/java tip

238. Product of Array Except Self

개구리는 개꿀개꿀 2021. 3. 24. 00:55

leetcode.com/problems/product-of-array-except-self/

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int multiple = 1;
        boolean isZero = false;
        int zeroCnt = 0;
        for(int num : nums) {
            if(num != 0) {
                multiple *= num;
            }
            if(num == 0) {
                isZero = true;
                zeroCnt++;
            }
        }
        
        int[] ans = new int[nums.length];
        if(isZero) {
            if(zeroCnt > 1) {
                return ans;
            } else {
                for(int i=0; i<nums.length; i++) {
                    if(nums[i] == 0) {
                        ans[i] = multiple;
                    }
                }    
            }
        } else {
            for(int i=0; i<nums.length; i++) {
                ans[i] = multiple/nums[i];
            }
        }
        return ans;
    }
}

leetcode.com/problems/product-of-array-except-self/discuss/65638/My-simple-Java-solution

 

My simple Java solution - LeetCode Discuss

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

public int[] productExceptSelf(int[] nums) {
    int[] result = new int[nums.length];
    for (int i = 0, tmp = 1; i < nums.length; i++) {
        result[i] = tmp;
        tmp *= nums[i];
    }
    for (int i = nums.length - 1, tmp = 1; i >= 0; i--) {
        result[i] *= tmp;
        tmp *= nums[i];
    }
    return result;
}