博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode Product of Array Except Self
阅读量:4562 次
发布时间:2019-06-08

本文共 1567 字,大约阅读时间需要 5 分钟。

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

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:

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


解题思路:

参考答案。

Because we cannot use division, so assume we have two integer arrays with the same length of nums, 

int[] leftProd = new int[nums.length]; int[] rightProd = new int[nums.length],

we store the product of all the left elements in leftProd and the product of all the right elements in rightProd,

then the product of leftProd[i] and rightProd[i] will be the value we want to put into the result.

Take the example of num[] = {2, 4, 3, 6}, then leftProd will be {1, 2, 8, 24} , and rightProd will be {72, 18, 6, 1}.


Java code:

public class Solution {    public int[] productExceptSelf(int[] nums) {        int[] result = new int[nums.length];        for(int i = 0; i < nums.length; i++) {            if( i == 0){                result[i] = 1;            }else{                result[i] = result[i-1] * nums[i-1];            }        }        int prod = 1;        for(int i = nums.length-1; i >= 0; i--){            result[i] *= prod;            prod *= nums[i];        }        return result;    }}

Reference:

1. https://leetcode.com/discuss/46150/java-o-n-solution-no-extra-space-with-explanation

 

转载于:https://www.cnblogs.com/anne-vista/p/4899729.html

你可能感兴趣的文章
React Children
查看>>
大数据等最核心的关键技术:32个算法
查看>>
Maven多模块项目搭建
查看>>
redis列表list
查看>>
雷林鹏分享: C# 简介
查看>>
ORA-12505: TNS: 监听程序当前无法识别连接描述符中所给出的SID等错误解决方法
查看>>
实用类-<Math类常用>
查看>>
构建之法阅读笔记之四
查看>>
10.15习题2
查看>>
Windows Server 2008 R2 备份与恢复详细实例
查看>>
Ubuntu上kubeadm安装Kubernetes集群
查看>>
关于java学习中的一些易错点(基础篇)
查看>>
MFC的多国语言界面的实现
查看>>
四则运算个人项目 最终版
查看>>
java线程系列---java5中的线程池
查看>>
SQL表连接
查看>>
新秀系列C/C++经典问题(四)
查看>>
memset函数具体说明
查看>>
经常使用的android弹出对话框
查看>>
确保新站自身站点设计的合理性的六大注意点
查看>>