1

#yyds干货盘点# LeetCode 腾讯精选练习 50 题:除自身以外数组的乘积

 1 year ago
source link: https://blog.51cto.com/u_13321676/5881636
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# LeetCode 腾讯精选练习 50 题:除自身以外数组的乘积

精选 原创

灰太狼_cxh 2022-11-23 18:30:40 博主文章分类:leetcode ©著作权

文章标签 数组 数据 时间复杂度 文章分类 Java 编程语言 阅读数224

给你一个整数数组 nums,返回 数组 answer ,其中 answer[i] 等于 nums 中除 nums[i] 之外其余各元素的乘积 。

题目数据 保证 数组 nums之中任意元素的全部前缀元素和后缀的乘积都在  32 位 整数范围内。

请不要使用除法,且在 O(n) 时间复杂度内完成此题。

输入: nums = [1,2,3,4]

输出: [24,12,8,6]

输入: nums = [-1,1,0,-3,3]

输出: [0,0,9,0,0]

代码实现:

class Solution {
public int[] productExceptSelf(int[] nums) {
int length = nums.length;
int[] answer = new int[length];

// answer[i] 表示索引 i 左侧所有元素的乘积
// 因为索引为 '0' 的元素左侧没有元素, 所以 answer[0] = 1
answer[0] = 1;
for (int i = 1; i < length; i++) {
answer[i] = nums[i - 1] * answer[i - 1];
}

// R 为右侧所有元素的乘积
// 刚开始右边没有元素,所以 R = 1
int R = 1;
for (int i = length - 1; i >= 0; i--) {
// 对于索引 i,左边的乘积为 answer[i],右边的乘积为 R
answer[i] = answer[i] * R;
// R 需要包含右边所有的乘积,所以计算下一个结果时需要将当前值乘到 R 上
R *= nums[i];
}
return answer;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK