Skip to content

Commit 19c48a4

Browse files
committed
优化238
1 parent 0359b85 commit 19c48a4

File tree

3 files changed

+14
-15
lines changed

3 files changed

+14
-15
lines changed

docs/0238-product-of-array-except-self.adoc

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ https://leetcode.cn/problems/product-of-array-except-self/[LeetCode - 238. 除
3535

3636
== 思路分析
3737

38+
利用 xref:0000-03-prefix-sum.adoc[Prefix Sum 前缀和] 的思路,分别求前缀乘积和后缀乘积,然后再逐个求每个元素的前后元素乘积。
39+
40+
利用结果数组存前缀乘积,可以将空间复杂度降低到常数级。
3841

3942
[[src-0238]]
4043
[tabs]

logbook/202503.adoc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1767,7 +1767,7 @@ endif::[]
17671767
|{counter:codes2503}
17681768
|{leetcode_base_url}/product-of-array-except-self/[238. 除自身以外数组的乘积^]
17691769
|{doc_base_url}/0238-product-of-array-except-self.adoc[题解]
1770-
|✅ 前缀和。利用前缀和的思路,分别求前缀乘积和后缀乘积,然后再逐个求每个元素的前后元素乘积。
1770+
|✅ 前缀和。利用前缀和的思路,分别求前缀乘积和后缀乘积,然后再逐个求每个元素的前后元素乘积。利用结果数组存前缀乘积,可以将空间复杂度降低到常数级。
17711771

17721772
|===
17731773

src/main/java/com/diguage/algo/leetcode/_0238_ProductOfArrayExceptSelf_3.java

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,25 @@
11
package com.diguage.algo.leetcode;
22

3-
import java.util.Arrays;
4-
53
public class _0238_ProductOfArrayExceptSelf_3 {
64
// tag::answer[]
5+
76
/**
87
* @author D瓜哥 · https://www.diguage.com
98
* @since 2025-10-22 19:31:52
109
*/
1110
public int[] productExceptSelf(int[] nums) {
12-
int[] prefix = new int[nums.length];
13-
Arrays.fill(prefix, 1);
14-
int[] suffix = new int[nums.length];
15-
Arrays.fill(suffix, 1);
16-
for (int i = 0; i < nums.length - 1; i++) {
17-
prefix[i] = (i - 1 >= 0 ? prefix[i - 1] : 1) * nums[i];
11+
// 先使用 result 存储前缀乘积
12+
int[] result = new int[nums.length];
13+
result[0] = nums[0];
14+
for (int i = 1; i < nums.length - 1; i++) {
15+
result[i] = result[i - 1] * nums[i];
1816
}
17+
int suffix = 1; // 利用变量 suffix 存放后缀乘积
1918
for (int i = nums.length - 1; i > 0; i--) {
20-
suffix[i] = (i + 1 < nums.length ? suffix[i + 1] : 1) * nums[i];
21-
}
22-
int[] result = new int[nums.length];
23-
for (int i = 0; i < nums.length; i++) {
24-
result[i] = (i - 1 >= 0 ? prefix[i - 1] : 1)
25-
* (i + 1 < nums.length ? suffix[i + 1] : 1);
19+
result[i] = result[i - 1] * suffix;
20+
suffix *= nums[i];
2621
}
22+
result[0] = suffix;
2723
return result;
2824
}
2925

0 commit comments

Comments
 (0)