leetcodetop100(15) 除自身以外数组的乘积已解答

给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 
题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在  32 位 整数范围内。请不要使用除法,且在 O(n) 时间复杂度内完成此题。

不用除法,对于数组中的位置num[i] 可以把它要求的数据看做左边的积L[i]乘以右边的积R[i]

左边的规则就是 L[i] = L[i-1]*nums[i-1]

右边的规则就是R[i-1] = R[i]*nums[i] 

代码:

package TOP11_20;

/**
 * 给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。
 * 

* 题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。 *

* 请不要使用除法,且在 O(n) 时间复杂度内完成此题。 *

*

*

* 示例 1: *

* 输入: nums = [1,2,3,4] * 输出: [24,12,8,6] */ public class Top15 { public static int[] productExceptSelf(int[] nums) { int len = nums.length; int[] L = new int[nums.length]; int[] R = new int[nums.length]; int[] res = new int[len]; // 上下三角 分为左边右边之积 L[0] = 1; for (int i = 0; i < len - 1; i++) { L[i+1] = L[i]*nums[i]; } R[len - 1] = 1; for (int i = len-1; i >0; i--) { R[i-1] = R[i]*nums[i]; } for (int i = 0; i < len; i++) { res[i] = L[i] * R[i]; } return res; } public static void main(String[] args) { int[] nums = {1,2,3,4}; int[] res = productExceptSelf(nums); System.out.println(res); } }

harryptter / LeetcodeTop100 · GitCode

你可能感兴趣的:(算法,算法,数据结构)