栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leetcode-238 除自身以外数组的乘积 [Java]

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode-238 除自身以外数组的乘积 [Java]

类别:数组 前缀和数组

题目:

想法:用两个数组head、tail存储一个位置前/后的所有数字的乘积,head和tail再按位相乘得到最终输出矩阵。

代码:

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] head = new int[n];
        int[] tail = new int[n];
        int i;
        //从前往后 head
        head[0]=1;
        head[1]=nums[0];
        //从后往前 tail
        tail[n-1]=1;
        tail[n-2]=nums[n-1];
        for(i=0;i 

结果:

优化:能不能只用一个矩阵存呢?使用一个中间变量k存储每一步的乘积。

代码:

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.length];
        int k = 1;
        for(int i = 0; i < res.length; i++){
            res[i] = k;
            k = k * nums[i]; // 此时数组存储的是除去当前元素左边的元素乘积
        }
        k = 1;
        for(int i = res.length - 1; i >= 0; i--){
            res[i] *= k; // k为该数右边的乘积。
            k *= nums[i]; // 此时数组等于左边的 * 该数右边的。
        }
        return res;
    }
}

作者:LDouble
链接:https://leetcode-cn.com/problems/product-of-array-except-self/solution/cheng-ji-dang-qian-shu-zuo-bian-de-cheng-ji-dang-q/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

结果:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/591700.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号