赞
踩
- public class ProductExceptSelf {
-
- public int[] productExceptSelf(int[] nums) {
-
- //每个answer[i]的值可以认为是nums[i]左右两侧的乘积
- //定义l和r两个数组分别存储nums[i]左右两侧的乘积
-
- int n = nums.length;
- int[] l = new int[n];
- int[] r = new int[n];
-
- l[0] = 1; //初始位置左侧无值,乘积为1
- for (int i = 1; i < n; i++) {
- l[i] = l[i-1] * nums[i-1];
- }
-
- r[n-1] = 1; //初始位置右侧无值,乘积为1
- for (int i = n-2; i >= 0; i--) {
- r[i] = r[i+1] * nums[i+1];
- }
-
- int[] answer = new int[n];
- for (int i = 0; i < n; i++) {
- answer[i] = l[i] * r[i]; //求结果
- }
-
- return answer;
- }
-
- public static void main(String[] args) {
- ProductExceptSelf self = new ProductExceptSelf();
- //int[] nums = {1,2,3,4};
- int[] nums = {-1,1,0,-3,3};
- System.out.println(Arrays.toString(self.productExceptSelf(nums)));
- }
- }

- public class ProductExceptSelf {
-
- public static void main(String[] args) {
- ProductExceptSelf self = new ProductExceptSelf();
- int[] nums = {1,2,3,4};
- //int[] nums = {-1,1,0,-3,3};
- System.out.println(Arrays.toString(self.productExceptSelf(nums)));
- }
-
- public int[] productExceptSelf(int[] nums) {
-
- //每个answer[i]的值可以认为是nums[i]左右两侧的乘积
- //( 出于对空间复杂度分析的目的,输出数组不被视为额外空间。)
- //同样的思路,但为了降低空间复杂度,去掉方法1定义的lr两个数组,让answer[i]先充当l数组得到一组值
- //然后在依次得到r的值并直接计算结果赋值到answer[i]
-
- int n = nums.length;
-
- int[] answer = new int[n];
- answer[0] = 1; //初始位置左侧无值,乘积为1
- for (int i = 1; i < n; i++) {
- answer[i] = answer[i-1] * nums[i-1];
- }
-
- int r = 1;
- answer[n-1] = r * answer[n-1];
- for (int i = n-2; i >= 0; i--) {
- r = r * nums[i+1];
- answer[i] = answer[i] * r;
- }
-
- return answer;
- }
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。