类别:数组 前缀和数组
题目:
想法:用两个数组head、tail存储一个位置前/后的所有数字的乘积,head和tail再按位相乘得到最终输出矩阵。
代码:
class Solution { public int[] productExceptSelf(int[] nums) { int n = nums.length; int[] head = new int[n]; int[] tail = new int[n]; int i; //从前往后 head head[0]=1; head[1]=nums[0]; //从后往前 tail tail[n-1]=1; tail[n-2]=nums[n-1]; for(i=0;i结果:
优化:能不能只用一个矩阵存呢?使用一个中间变量k存储每一步的乘积。
代码:
class Solution { public int[] productExceptSelf(int[] nums) { int[] res = new int[nums.length]; int k = 1; for(int i = 0; i < res.length; i++){ res[i] = k; k = k * nums[i]; // 此时数组存储的是除去当前元素左边的元素乘积 } k = 1; for(int i = res.length - 1; i >= 0; i--){ res[i] *= k; // k为该数右边的乘积。 k *= nums[i]; // 此时数组等于左边的 * 该数右边的。 } return res; } } 作者:LDouble 链接:https://leetcode-cn.com/problems/product-of-array-except-self/solution/cheng-ji-dang-qian-shu-zuo-bian-de-cheng-ji-dang-q/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)