• 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
    ~~~~~
  • 相关阅读:
    剑指offer51-正则表达式匹配
    剑指offer50-构建乘积数组
    剑指offer49-数组中的重复
    PHP系列笔记——Zend_Controller工作流程
    多态与重载
    读取文件数据的大概流程
    基于HTTP协议下载文件的实现
    C++中的面向对象笔记
    firebreath注册接口
    python读取excelxlsx,写入excel
  • 原文地址:https://www.cnblogs.com/missmzt/p/5478291.html
Copyright © 2020-2023  润新知