LeetCode刷题-top100( 除自身以外数组的乘积)
238. 除自身以外数组的乘积
给你一个整数数组 nums
,返回 数组 answer
,其中 answer[i]
等于 nums
中除 nums[i]
之外其余各元素的乘积 。
题目数据 保证 数组 nums
之中任意元素的全部前缀元素和后缀的乘积都在 32 位 整数范围内。
请 不要使用除法,且在 O(n)
时间复杂度内完成此题。
示例 1:
输入: nums =[1,2,3,4]
输出:[24,12,8,6]
示例 2:
输入: nums = [-1,1,0,-3,3] 输出: [0,0,9,0,0]
根据要求代码只有一种做法,利用左右指针实现错位相乘
class Solution {public int[] productExceptSelf(int[] nums) {int n = nums.length;int[] answer = new int[n];// 计算左侧乘积int leftProduct = 1;for (int i = 0; i < n; i++) {answer[i] = leftProduct;leftProduct *= nums[i];}// 计算右侧乘积并同时计算最终结果int rightProduct = 1;for (int i = n - 1; i >= 0; i--) {answer[i] *= rightProduct;rightProduct *= nums[i];}return answer;}
}