classSolution{publicint[]productExceptSelf(int[] nums){// 不用考虑溢出int len = nums.length;int[] ans =newint[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;}}
更新版
classSolution{publicint[]productExceptSelf(int[] nums){int[] ans =newint[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;}}
文章目录题目描述思路 & 代码题目描述首先暴力二层循环肯定可以,然后先累乘整个数组,再用除法肯定也行。但是很遗憾,两种做法都不满足题目说明。思路 & 代码O(n) & O(1)考虑到这个核心:ans[i] 就是当前元素左边累乘 * 右边累乘那么完全可以分成左边开始的累乘遍历 + 右边开始的累乘遍历具体见代码 & 注释class Solution { public int[] productExceptSelf(int[] nums) {