Product of arrays other than itself-LeetCode

topic:

Insert picture description here

Original link: https://leetcode-cn.com/problems/product-of-array-except-self

Ideas:

  1. At first I want to use division, first multiply all of them, and then divide each one by the current element value. Then there is a special case of 0, and the title is limited.
  2. So we can use a similar iterative idea, for each element outside the multiplication and integration into two parts before and after, multiplexing the output array, reducing space occupation

Code:

class Solution {
    
    
    public int[] productExceptSelf(int[] nums) {
    
    
        int[] result = new int[nums.length];
        if(nums.length<=0) return result;

        // 前缀元素,复用空间
        result[0] = 1;
        for(int i =1;i<nums.length;i++){
    
    
            result[i] = result[i-1]*nums[i-1];
        }

        // 后缀元素
        int R = 1;
        for(int i = nums.length-1;i>=0;i--){
    
    
            result[i] = result[i]*R;
            R*=nums[i];
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/qq_35221523/article/details/113101283