146 - 238 除自身外数组的乘积
题目
给定长度为 n 的整数数组 nums,其中 n > 1,返回输出数组 output ,其中 output[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积。
示例:
输入: [1,2,3,4] 输出: [24,12,8,6]
说明: 请不要使用除法,且在 O(n) 时间复杂度内完成此题。
进阶: 你可以在常数空间复杂度内完成这个题目吗?( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
解答
第一反应,就是暴力相乘。。
两次遍历
一个非常巧妙的做法。
前后遍历两次,前往后遍历,乘一下除了该位,左边的乘积。也就是累乘在一个数里面。
后往前遍历也是一样,乘一下右边的乘积。
Runtime: 120 ms, faster than 98.57% of Python3 online submissions for Product of Array Except Self.
Memory Usage: 19.4 MB, less than 96.00% of Python3 online submissions for Product of Array Except Self.
Runtime: 96 ms, faster than 27.36% of JavaScript online submissions for Product of Array Except Self.
Memory Usage: 42.7 MB, less than 16.00% of JavaScript online submissions for Product of Array Except Self.
Runtime: 1544 ms, faster than 25.89% of Go online submissions for Product of Array Except Self.
Memory Usage: 9.1 MB, less than 100.00% of Go online submissions for Product of Array Except Self.
Last updated
Was this helpful?