Skip to content

Commit 6abae41

Browse files
committed
238.除自身以外数组的乘积,前缀和
1 parent 61070a4 commit 6abae41

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@
9494
232. 用栈实现队列
9595
234. 回文链表
9696
236. 二叉树的最近公共祖先
97+
238. 除自身以外数组的乘积
9798
239. 滑动窗口最大值
9899
240. 搜索二维矩阵 II
99100
279. 完全平方数

leetcode_Java/DoneType.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@
166166
136. 只出现一次的数字(哈希表,列表,位运算)
167167
169. 多数元素(排序,哈希表,投票,计数,分治)
168168
215. 数组中的第K个最大元素(快速排序,堆排序)
169+
238. 除自身以外数组的乘积(前缀和)
169170
239. 滑动窗口最大值(单调递减双端队列)
170171
240. 搜索二维矩阵 II(二分查找)
171172
283. 移动零(双指针)

leetcode_Java/Solution0238.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// 238. 除自身以外数组的乘积
2+
3+
4+
/*
5+
前缀和:
6+
1、当前数 = 左边的乘积 x 右边的乘积
7+
2、初始化结果数组为1,方便乘积时保留左右部分的值
8+
3、遍历数组,从左到右计算时,当前位置的值为左部分的乘积;从右到左计算时,当前位置的值为右部分的乘积;
9+
两次计算都没有将当前位置的值加入乘积,最终当前位置的值就是 左边的乘积 x 右边的乘积
10+
11+
nums 5 2 3 4
12+
res 1 1 1 1
13+
l 1 5 5*2 5*2*3
14+
r 4*3*2 4*3 4 1
15+
*/
16+
class Solution {
17+
public int[] productExceptSelf(int[] nums) {
18+
int l = 1, r = 1, n = nums.length;
19+
int[] res = new int[n];
20+
Arrays.fill(res, 1);
21+
for (int i = 0; i < n; i++) {
22+
res[i] *= l;
23+
l *= nums[i];
24+
res[n - i - 1] *= r;
25+
r *= nums[n - i - 1];
26+
}
27+
return res;
28+
}
29+
}

0 commit comments

Comments
 (0)