Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[나리] WEEK 03 Solutions #386

Merged
merged 5 commits into from
Aug 30, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 74 additions & 0 deletions product-of-array-except-self/naringst.js
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

안녕하세요 나리님, 나누기 연산자를 사용하면 안 된다고 문제에 적혀 있습니다.

You must write an algorithm that runs in O(n) time and without using the division operation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

앗 해당 문장을 못봣네요 ㅜㅜ 😨

Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* @param {number[]} nums
* @return {number[]}
*/

/**
* Runtime: 124ms, Memory: 65.06MB
* Time complexity: O(n^2)
* Space complexity: O(n)
* -> answer 배열에 O(n)
* -> splicedArr 배열에 O(n)
*/

var productExceptSelf = function (nums) {
const totalProduct = nums.reduce((total, current) => total * current, 1);
const answer = Array(nums.length).fill(0);

for (let i = 0; i < nums.length; i++) {
answer[i] = totalProduct / nums[i];
if (nums[i] === 0) {
const splicedArr = nums.filter(function (_, index) {
return index !== i;
});
answer[i] = splicedArr.reduce((total, current) => total * current, 1);
}
}

return answer;
};

/**
* @param {number[]} nums
* @return {number[]}
*/

/**
* 위의 풀이는 0일 때마다 순회를 해야 하기 때문에 해당 부분을 0의 개수를 세어 처리하도록 변경한 풀이

* Runtime: 109ms, Memory: 63.45MB
* Time complexity: O(n)
* Space complexity: O(n)

*/
var productExceptSelf = function (nums) {
let totalProduct = 1;
let zeroCount = 0;
const answer = Array(nums.length).fill(0);

for (let numIndex = 0; numIndex < nums.length; numIndex++) {
if (nums[numIndex] === 0) {
zeroCount += 1;
} else {
totalProduct *= nums[numIndex];
}
}

for (let i = 0; i < nums.length; i++) {
if (nums[i] === 0) {
if (zeroCount - 1 > 0) {
answer[i] = 0;
} else {
answer[i] = totalProduct;
}
} else {
if (zeroCount > 0) {
answer[i] = 0;
} else {
answer[i] = totalProduct / nums[i];
}
}
}

return answer;
};