zoukankan      html  css  js  c++  java
  • leetcode 之 Product of Array Except Self

    原问题描述:  难度: 中等

    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]

    中文描述:

    给定一个n维的整数数组nums,(n>1),  返回一个n维数组output,并且output[i] 的值为 nums数组中除了nums[i] 之外的所有元素的乘积。

    如, 给定nums = [1, 2, 3, 4] 返回:[24, 12, 8, 6]

    解答:

    看到这个问题第一反应就是,首先计算nums 所有元素的乘积 pro,然后遍历nums, 用 pro/nums[i] 作为output[i]的取值。 但是看到题目要求说能不能不用除法,仔细思考,除法的话,还要考虑nums[i] = 0 的情况,会变得比较复杂。

    然后参考他人思想, 得到解决方法:

    1.  顺序遍历nums 数组,将output[i] 的值设为 i 之前元素的乘积。

    2. 逆序遍历nums数组, 将output[i]的值,乘上i之后元素的乘积。

    3. 输出output

    算法思想很简单,但是不容易想到,之前有个分发糖果的问题,也是通过顺序遍历和逆序遍历相结合实现的。

    算法python的实现:

    class Solutin(object):
        def productExceptionSelf(self, nums):
            res = 1
            le = len(nums)
            output = []
            for i in nums:
                output.append(res)
                res *= nums[i]
            res = 1
            for i in range(le-1, -1, -1):
                output[i] *= res
                res *= nums[i]
            return output
    View Code
    ~~~~~
  • 相关阅读:
    Idea默认的全局设置,如Maven等
    mybatis中Parameter index out of range (1 > number of parameters, which is 0).
    SpringBoot入门-2(两种热部署方式)
    Java中关于static语句块的理解
    HashMap源码剖析
    keytool用法总结
    Tomcat配置https
    git的安装及其使用
    java中Arrays类的应用
    三次握手四次挥手
  • 原文地址:https://www.cnblogs.com/missmzt/p/5478291.html
Copyright © 2011-2022 走看看