30-Day Leetcoding Challenge Day15

用两个数组分别记录左边和右边得乘积

L[i] = L[i-1]*nums[i-1];

R[i] = R[i+1]*nums[i+1];

nums[i] = L[i]*R[i];

 

JAVA

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] left = new int[n];
        int[] right = new int[n];
        Arrays.fill(left,1);
        Arrays.fill(right,1);
        for(int i = 1; i < n; i++){
            left[i] = left[i-1]*nums[i-1];
        }
        for(int i = n-2; i >= 0; i--){
            right[i] = right[i+1]*nums[i+1];
        }
        for(int i = 0; i < n; i++){
            nums[i] = left[i]*right[i];
        }
        return nums;
    }
}

 

Python3

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        res = []
        left = [1]*len(nums)
        right = [1]*len(nums)
        for i in range(1, len(nums)):
            left[i] = left[i-1]*nums[i-1]
        for i in range(len(nums)-2, -1, -1):
            right[i] = right[i+1]*nums[i+1]
        for i in range(len(nums)):
            res.append(left[i]*right[i])
        return res

 

posted @ 2020-04-17 14:20  yawenw  阅读(60)  评论(0编辑  收藏  举报