본문 바로가기

Amazon/Leetcode

238. Product of Array Except Self

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)



<SOLVE>


class Solution {
    public int[] productExceptSelf(int[] nums) {
       
        int[] result = new int[nums.length];
 
        int[] t1 = new int[nums.length];
        int[] t2 = new int[nums.length];

        t1[0]=1;
        t2[nums.length-1]=1;

        //scan from left to right
        for(int i=0; i<nums.length-1; i++){
            t1[i+1] = nums[i] * t1[i];
        }

        //scan from right to left
        for(int i=nums.length-1; i>0; i--){
            t2[i-1] = t2[i] * nums[i];
        }

        //multiply
        for(int i=0; i<nums.length; i++){
            result[i] = t1[i] * t2[i];
        }

        return result;
    }
}

'Amazon > Leetcode' 카테고리의 다른 글

200. Number of Islands  (0) 2018.08.08
17. Letter Combinations of a Phone Number  (0) 2018.08.04
141. Linked List Cycle  (0) 2018.08.03
155. Min Stack  (0) 2018.08.02
819. Most Common Word  (0) 2018.08.01