[leetcode]238. Product of Array Except Self

2023-05-16

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.)

Solution:

求出数组的所有乘积和,对应位置除一下。

class Solution {
    public int[] productExceptSelf(int[] nums) {
        if(nums == null || nums.length == 0) {
            return null;
        }
        int n = nums.length;
        int[] output = new int[n];
        int total = 1;
        for(int i = 0; i < n; i++) {
            total *= nums[i];
        }
        
        for(int j = 0; j < n; j++) {
            output[j] = total/nums[j];
        }
        return output;
    }   
}

但是有个问题,如果输入数组里面有数字为0的话,就会出错,上述程序没有考虑这种情况,优化:

class Solution {
    public int[] productExceptSelf(int[] nums) {
        if(nums == null || nums.length == 0) {
            return null;
        }
        int n = nums.length;
        int[] output = new int[n];
        int total = 1;
        for(int i = 0; i < n; i++) {
            total *= nums[i];
        }
        if(total == 0) {
            for(int k = 0; k < n; k++) {
                output[k] = calculate(nums,k);
            }
        }else{
            for(int j = 0; j < n; j++) {
                output[j] = total/nums[j];
            }
        }
        return output;
    }   
    public int calculate(int[] nums,int k) {
        int res = 1;
        for(int i = 0; i < nums.length; i++) {
            if(i == k) {
                continue;
            }else {
                res *= nums[i];
            }
        }
        return res;
    }
}

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

[leetcode]238. Product of Array Except Self 的相关文章

  • B树、B+树及索引

    B树 xff1a 每个节点都存储key和data xff0c 所有节点组成这棵树 xff0c 并且叶子节点指针为null B 43 树 xff1a 只有叶子节点存储data xff0c 叶子节点包含了这棵树的所有键值 xff0c 叶子节点不

随机推荐

  • Arrays.sort和Collections.sort实现原理解析

    Collections sort方法底层就是调用的Arrays sort方法 写一个例子看源码 xff1a public static void main String args List lt String gt strings 61 A
  • Java代理模式之动态代理

    代理模式是设计模式中非常重要的一种类型 代理模式从类型上来说 xff0c 可以分为静态代理和动态代理两种类型 假设一个场景 xff0c 有一个蛋糕店 xff0c 卖的蛋糕都是用蛋糕机做的 xff0c 而且不同种类的蛋糕由不同的蛋糕机来做 x
  • 二叉树镜像

    求二叉树镜像 public class Solution public void Mirror TreeNode root if root 61 61 null return if root left 61 61 null amp amp
  • 设计模式之适配器模式

    适配器模式是作为两个不兼容的接口之间的桥梁 这种类型的设计模式属于结构型模式 xff0c 它结合了两个独立接口的功能 这种模式涉及到一个单一的类 xff0c 该类负责加入独立的或不兼容的接口功能 举个真实的例子 xff0c 读卡器是作为内存
  • 设计模式之单例模式

    1 懒汉式 xff0c 线程不安全 public class Demo1 private static Demo1 instance private Demo1 public static Demo1 getInstance if inst
  • Lambda表达式详解

    Java 8最值得学习的特性就是Lambda表达式 Lambda写的好可以极大减少代码冗余 xff0c 同时可读性也好过冗长的内部类 xff0c 匿名类 举例说明一下 xff1a xff08 1 xff09 创建线程传统写法 xff1a T
  • Android8.0以上实现APP(应用)开机自启动

    一 程序中实现APP开机自启动 可参考 xff1a https www cnblogs com jetereting p 4572302 html 二 设置APP开机自启动权限 小米手机设置开机启动应用权限 xff08 Android9 0
  • 跳台阶问题

    1 输出斐波那契数列的第n项 直接上代码 xff1a public class Fibonacci public static int fibonacci int n if n 61 61 0 return 0 if n 61 61 1 r
  • 字符串编辑距离

    字符串的编辑距离 xff0c 又称为Levenshtein距离 是利用字符操作 xff0c 把字符串A转换成字符串B所需要的最少操作数 其中 xff0c 字符操作包括 xff1a 删除一个字符插入一个字符修改一个字符 例如对于 34 hel
  • [leetcode]807.Max Increase to Keep City Skyline

    In a 2 dimensional array grid each value grid i j represents the height of a building located there We are allowed to in
  • [leetcode]1038. Binary Search Tree to Greater Sum Tree

    Given the root of a binary search tree with distinct values modify it so that every node has a new value equal to the su
  • [leetcode]344. Reverse String

    Write a function that reverses a string The input string is given as an array of characters char Do not allocate extra s
  • [leetcode]136. Single Number

    Given a non empty array of integers every element appears twice except for one Find that single one Note Your algorithm
  • [leetcode]412. Fizz Buzz

    Write a program that outputs the string representation of numbers from 1 to n But for multiples of three it should outpu
  • [leetcode]94. Binary Tree Inorder Traversal

    Given a binary tree return the inorder traversal of its nodes 39 values Example Input 1 null 2 3 1 2 3 Output 1 3 2 Solu
  • [leetcode]46. Permutations

    Given a collection of distinct integers return all possible permutations Example Input 1 2 3 Output 1 2 3 1 3 2 2 1 3 2
  • [ERROR][idea报错]Unmapped Spring configuration files found.

    idea启动Event Log提示 xff1a Spring Configuration Check Unmapped Spring configuration files found Please configure Spring fac
  • (备忘)android模拟器摄像头模拟

    Camera分Front Camera和Back Camera 通常我们模拟后摄像头就可以了 三个选项 none 表示没有摄像头 打开摄像应用会崩溃 emulated 系统模拟一个动态的画面 在黑白格背景上随机移动的矩形色块 Webcam
  • [leetcode]22. Generate Parentheses

    Given n pairs of parentheses write a function to generate all combinations of well formed parentheses For example given
  • [leetcode]238. Product of Array Except Self

    Given an array nums of n integers where n gt 1 return an array output such that output i is equal to the product of all