leetcode 238. 除自身以外数组的乘积

2023.11.13

leetcode 238. 除自身以外数组的乘积_第1张图片

        本题用双循环暴力法会超时,使用除法的话,分母又会为0。 于是上评论区查看解法,大致思路是定义两个数组left和right,left[i]和right[i]分别记录当前元素 i 左边和右边的乘积。 特别的,left第一个元素需初始化为1,right最后一个元素也需初始化为1。 

        java代码如下:

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] left = new int[nums.length];
        int[] right = new int[nums.length];
        int[] ans = new int[nums.length];
        left[0] = 1;
        right[nums.length-1] = 1;
        //遍历赋值left和right数组
        for(int i=1; i=0; i--){
            right[i] = right[i+1] * nums[i+1];
        }
        //遍历赋值ans数组
        for(int i=0; i

你可能感兴趣的:(leetcode专栏,leetcode,算法,java,数据结构)