力扣热题100道之238除自身以外数组的乘积

解法

解法1:构建左右两边的乘积数组

l[0]=1,r[n-1]=1;然后 l[i]=l[i-1]*nums[i-1],r[j]=r[j+1]*nums[j+1]。

复制代码
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n=nums.length;
        int[]l=new int[n];
        int[]r=new int[n];
        int[]result=new int[n];
        l[0]=1;
        r[n-1]=1;
        int i=1;
        int j=n-2;
        while(i<n){
            l[i]=l[i-1]*nums[i-1];
            i++;
        }
        while(j>=0){
            r[j]=r[j+1]*nums[j+1];
            j--;
        }
        for(int p=0;p<n;p++){
            result[p]=l[p]*r[p];
        }
        return result;
    }
}
解法2:空间复杂度为O(1)的解法

将result数组(输出答案的数组)作为L数组,先将l数组求出来,然后定义一个变量r一直更新来代替r数组的功能。

复制代码
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n=nums.length;
        int[]result=new int[n];
        int i=1;
        result[0]=1;
        
        while(i<n){
            result[i]=result[i-1]*nums[i-1];
            i++;
        }
        int j=n-2;
        int r=nums[n-1];
        while(j>=0){  
            result[j]=result[j]*r;
            r=r*nums[j];
            j--;
        }
        return result;
    }
}
历史解法
报错超出预期时间的解法

遍历数组,当不是当前遍历的元素的时候,找到其他元素的乘积。这种方法的时间复杂度是O(n2),不符合题意。

复制代码
class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n=nums.length;
        int[]result=new int[n];
        int[]muls=new int[n-1];
        for(int i=0;i<n;i++){
            int mul=1;
            for(int j=0;j<n;j++){
                if(j!=i){
                    mul=mul*nums[j];
                }
                if(j==n-1||i==n-1&&j==n-2){
                    result[i]=mul;
                }
            }
        }
        return result;
    }
}
相关推荐
天赐学c语言7 分钟前
12.19 - 买卖股票的最佳时机 && const的作用
c++·算法·leecode
菜鸟233号11 分钟前
力扣78 子集 java实现
java·数据结构·算法·leetcode
yesyesyoucan14 分钟前
在线魔方解谜站:从零入门到精通的智能魔方学习平台
学习·算法
Han.miracle15 分钟前
数据结构与算法--008四数之和 与经典子数组 / 子串问题解析
数据结构·算法
!停16 分钟前
字符函数和字符串函数
算法
AI科技星31 分钟前
圆柱螺旋运动方程的一步步求导与实验数据验证
开发语言·数据结构·经验分享·线性代数·算法·数学建模
FONE_Platform1 小时前
FONE食品饮料行业全面预算解决方案:构建韧性增长
人工智能·算法·全面预算·全面预算管理系统·企业全面预算
月明长歌1 小时前
【码道初阶】【Leetcode94&144&145】二叉树的前中后序遍历(非递归版):显式调用栈的优雅实现
java·数据结构·windows·算法·leetcode·二叉树
DanyHope1 小时前
《LeetCode 49. 字母异位词分组:哈希表 + 排序 全解析》
算法·leetcode·哈希算法·散列表
iAkuya1 小时前
(leetcode) 力扣100 15轮转数组(环状替代)
数据结构·算法·leetcode