当前位置:   article > 正文

力扣(LeetCode) 238.除自身以外数组的乘积(java)_productexceptself

productexceptself

题目

方法一:定义两个新数组

  1. public class ProductExceptSelf {
  2. public int[] productExceptSelf(int[] nums) {
  3. //每个answer[i]的值可以认为是nums[i]左右两侧的乘积
  4. //定义l和r两个数组分别存储nums[i]左右两侧的乘积
  5. int n = nums.length;
  6. int[] l = new int[n];
  7. int[] r = new int[n];
  8. l[0] = 1; //初始位置左侧无值,乘积为1
  9. for (int i = 1; i < n; i++) {
  10. l[i] = l[i-1] * nums[i-1];
  11. }
  12. r[n-1] = 1; //初始位置右侧无值,乘积为1
  13. for (int i = n-2; i >= 0; i--) {
  14. r[i] = r[i+1] * nums[i+1];
  15. }
  16. int[] answer = new int[n];
  17. for (int i = 0; i < n; i++) {
  18. answer[i] = l[i] * r[i]; //求结果
  19. }
  20. return answer;
  21. }
  22. public static void main(String[] args) {
  23. ProductExceptSelf self = new ProductExceptSelf();
  24. //int[] nums = {1,2,3,4};
  25. int[] nums = {-1,1,0,-3,3};
  26. System.out.println(Arrays.toString(self.productExceptSelf(nums)));
  27. }
  28. }

LeetCode测试结果

 

方法二:对方法一进行空间压缩

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

LeetCode测试结果

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/857458
推荐阅读
相关标签
  

闽ICP备14008679号