【LeetCode笔记】238. 除自身以外数组的乘积(Java、思路题)

题目描述

  • 首先暴力二层循环肯定可以,然后先累乘整个数组,再用除法肯定也行。
  • 但是很遗憾,两种做法都不满足题目说明。
    在这里插入图片描述

思路 & 代码

  • O(n) & O(1)
  • 考虑到这个核心:ans[i] 就是当前元素左边累乘 * 右边累乘
  • 那么完全可以分成左边开始的累乘遍历 + 右边开始的累乘遍历
  • 具体见代码 & 注释
class Solution {
    public int[] productExceptSelf(int[] nums) {
        // 不用考虑溢出
        int len = nums.length;
        int[] ans = new int[len];
        // ans[i]值看成:当前数左边累乘 * 右边累乘
        // 1. 先把ans[i]变成“当前数左边累乘”
        int temp = 1;
        for(int i = 0; i < len; i++){
            ans[i] = temp;
            temp *= nums[i];
        }
        // 2. 然后用“右边数累乘”来乘ans[i];
        temp = 1;
        for(int i = len - 1; i >= 0; i--){
            ans[i] *= temp;
            temp *= nums[i];
        }
        return ans;
    }
}

更新版

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] ans = new int[nums.length];
        for(int i = 0, pre = 1; i < nums.length; i++) {
            ans[i] = pre;
            pre *= nums[i];
        }
        for(int i = nums.length - 1, next = 1; i >= 0; i--) {
            ans[i] *= next;
            next *= nums[i]; 
        }
        return ans;
    }
}

版权声明:本文为qq_45108415原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。