Skip to content

Commit dda20bf

Browse files
Merge pull request #26 from undefined-dev74:practice
Practice
2 parents 8ecf194 + c310a3c commit dda20bf

File tree

1 file changed

+48
-12
lines changed

1 file changed

+48
-12
lines changed

src/leetcode/Medium/productExceptSelf.js

Lines changed: 48 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,55 @@ function productExceptSelf(nums) {
3333
}
3434

3535
function productExceptSelf_second(nums) {
36-
let total = 1;
37-
let i = 0;
38-
let finalResult = [];
39-
while (i < nums.length) {
40-
total = nums[i] * total;
41-
i++;
36+
let product_without_zero = 1;
37+
let count_of_zero = 0;
38+
39+
for (let i = 0; i < nums.length; i++) {
40+
if (nums[i] === 0) {
41+
count_of_zero++;
42+
} else {
43+
product_without_zero *= nums[i];
44+
}
4245
}
43-
i = 0;
44-
while (i < nums.length) {
45-
finalResult[i] = total / nums[i];
46-
i++;
46+
47+
let results = Array(nums.length);
48+
49+
for (let i = 0; i < nums.length; i++) {
50+
const element = nums[i];
51+
if (element !== 0) {
52+
if (count_of_zero > 0) results[i] = 0;
53+
else {
54+
results[i] = product_without_zero / element;
55+
}
56+
} else {
57+
if (count_of_zero > 1) results[i] = 0;
58+
else results[i] = product_without_zero;
59+
}
4760
}
48-
console.log(total);
61+
return results;
4962
}
50-
productExceptSelf([1, 2, 3, 4]);
63+
64+
function productExceptSelf_third(nums) {
65+
let n = nums.length;
66+
let left = Array(n);
67+
let right = Array(n);
68+
left[0] = 1;
69+
right[n - 1] = 1;
70+
let results = Array(n);
71+
72+
for (let i = 1; i < n; i++) {
73+
left[i] = nums[i - 1] * left[i - 1];
74+
}
75+
for (let i = n - 2; i >= 0; i--) {
76+
right[i] = nums[i + 1] * right[i + 1];
77+
}
78+
for (let i = 0; i < n; i++) {
79+
results[i] = left[i] * right[i];
80+
}
81+
console.log(results);
82+
return results;
83+
}
84+
85+
// productExceptSelf([1, 2, 3, 4]);
5186
productExceptSelf_second([1, 2, 3, 4]);
87+
productExceptSelf_third([1, 2, 3, 4]);

0 commit comments

Comments
 (0)