Leetcode Hot 100刷题记录 -Day13(除自身以外数组的乘积)

除自身以外数组的乘积

问题描述:

        给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。

        题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在  32 位 整数范围内。

        请 不要使用除法,且在 O(n) 时间复杂度内完成此题。

示例 1:

输入: nums = [1,2,3,4]

输出: [24,12,8,6]

示例 2:

输入: nums = [-1,1,0,-3,3]
输出: [0,0,9,0,0]

思路分析:

238. 除自身以外数组的乘积 - 力扣(LeetCode)icon-default.png?t=O83Ahttps://leetcode.cn/problems/product-of-array-except-self/solutions/272369/chu-zi-shen-yi-wai-shu-zu-de-cheng-ji-by-leetcode-/?envType=study-plan-v2&envId=top-100-liked

//提交版
class Solution {
    public int[] productExceptSelf(int[] nums) {
         int n = nums.length;
        int[] L = new int[n];
        int[] R = new int[n];
        int[] answer = new int[n];
        L[0] = 1;
        R[n-1] = 1;
        for (int i = 1; i < n;i++){
            L[i] = L[i - 1] * nums[i - 1];
        }
        for (int j=n-2 ; j >= 0;j--){
            R[j] = R[j+1] * nums[j+1];
        }
        for (int i =0;i<n;i++){
            answer[i] = L[i] * R[i];
        }
        return answer;
    }
}


//带有输入输出版
import java.util.Arrays;

public class hot_14productExceptSelf {
    public int[] productExceptSelf(int[] nums){
        int n = nums.length;
        int[] L = new int[n];
        int[] R = new int[n];
        int[] answer = new int[n];
        L[0] = 1;
        R[n-1] = 1;
        for (int i = 1; i < n;i++){
            L[i] = L[i - 1] * nums[i - 1];
        }
        //注意边界线的判断
        // 在这里新数组R[0]应该存储值,所以需要能取到0
        for (int j=n-2 ; j >= 0;j--){
            R[j] = R[j+1] * nums[j+1];
        }
        for (int i =0;i<n;i++){
            answer[i] = L[i] * R[i];
        }
        return answer;
    }
    public static void main(String[] args){
        int[] nums = {1,2,3,4};
        System.out.println("输入:nums = " + Arrays.toString(nums));
        hot_14productExceptSelf hot14productExceptSelf = new hot_14productExceptSelf();
        int[] result = hot14productExceptSelf.productExceptSelf(nums);
        System.out.println("输出 = " + Arrays.toString(result));
    }
}

知识点总结:

  • 注意边界线的判断,R[0]应该能被取到
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值