Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd04ef97

Browse files
authored
Merge pull requestneetcode-gh#593 from Basit-Imam/main
Update 238-Product-of-Array-Except-Self.java
2 parents9d051d1 +713492c commitd04ef97

File tree

1 file changed

+11
-15
lines changed

1 file changed

+11
-15
lines changed
Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,20 @@
11
//Just store the left and right product (Try doing this with extra space first)
22
//This one is constant space because we are returning the array we created
3+
//In first pass calculate the left product except self and in second calculate the right
34

45
classSolution {
56

67
publicint[]productExceptSelf(int[]nums) {
78
int[]arr =newint[nums.length];
8-
arr[0] =1;
9-
for (inti =1;i <nums.length;i++) {
10-
arr[i] =arr[i -1] *nums[i -1];
11-
}
12-
intprod =nums[nums.length -1];
13-
nums[nums.length -1] =1;
14-
for (inti =nums.length -2;i >=0;i--) {
15-
intstore =nums[i];
16-
nums[i] =nums[i +1] *prod;
17-
prod =store;
18-
}
19-
for (inti =0;i <nums.length;i++) {
20-
arr[i] =arr[i] *nums[i];
21-
}
22-
returnarr;
9+
intright=1,left=1;
10+
for (inti =0;i <nums.length;i++) {
11+
arr[i] =left;
12+
left *=nums[i];
13+
}
14+
for(inti =nums.length -1;i >=0;i--) {
15+
arr[i] *=right;
16+
right *=nums[i];
17+
}
18+
returnarr;
2319
}
2420
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp