您的位置:首页 > 编程语言 > Python开发

LeetCode238 Product of Array Except Self(java and python solution)

2016-12-06 11:49 573 查看
题目要求:

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.)

Subscribe to see which companies asked this question

难点:

本题不能使用除法,所以只能使用循环相乘的方式进行处理

首先:

(1)正向记录乘积

(2)然后反向记录乘积

(3)对应位置相乘

java solution

// 使用正序循环扫描相乘与后续循环扫描相乘的方法进行处理
public class Solution {
public int[] productExceptSelf(int[] nums) {
int[] temple1 = new int[nums.length];
int[] temple2 = new int[nums.length];
for(int i = 0; i < nums.length; i++) {
if(i == 0) temple1[i] = 1;
else temple1[i] = temple1[i - 1] * nums[i - 1];
}
for(int i = nums.length - 1; i >= 0; i--) {
if(i == nums.length - 1) temple2[i] = 1;
else temple2[i] = temple2[i + 1] * nums[i + 1];
}
for(int i = 0; i < nums.length; i++) {
nums[i] = temple1[i] * temple2[i];
}
return nums;
}
}


python solution

class Solution(object):
def productExceptSelf(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
temple1 = []
temple2 = []
for index in range(len(nums)):
if index == 0:
temple1.append(1)
else:
temple1.append(temple1[index - 1] * nums[index - 1])
i = 0
for index in range(len(nums))[::-1]:
if index == len(nums) - 1:
temple2.append(1)
else:
temple2.append(temple2[i - 1] * nums[index + 1])
i += 1
temple2.reverse()

for index in range(len(nums)):
nums[index] = temple1[index] * temple2[index]

return nums
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: