Skip to content

Commit

Permalink
add: solve #239 Product of Array Except Self with ts
Browse files Browse the repository at this point in the history
  • Loading branch information
Yjason-K committed Dec 27, 2024
1 parent e8d4b4a commit e1d144d
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions product-of-array-except-self/Yjason-K.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* ์ฃผ์–ด์ง„ ๋ฐฐ์—ด์—์„œ ์ž์‹ ์˜ ์ธ๋ฑ์Šค๋ฅผ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ์š”์†Œ๋“ค์˜ ๊ณฑ์„ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜
*
* @param {number[]} nums - ์ •์ˆ˜ ๋ฐฐ์—ด
* @returns {number[]} - ๊ฐ ์ธ๋ฑ์Šค์˜ ์š”์†Œ๋ฅผ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€ ์š”์†Œ๋“ค์˜ ๊ณฑ์„ ๊ตฌํ•œ ๋ฐฐ์—ด
*
* 1. ๊ฒฐ๊ณผ ๋ฐฐ์—ด `result`๋ฅผ 1๋กœ ์ดˆ๊ธฐํ™”.
* 2. ์™ผ์ชฝ์—์„œ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ์ˆœํšŒํ•˜๋ฉฐ `left` ๊ฐ’์„ ์ด์šฉํ•ด ๊ธฐ์ค€ idx ์ด์ „์˜ ๊ฐ’์„ ๊ณ„์‚ฐํ•˜์—ฌ `result`์— ์ €์žฅ.
* 3. ์˜ค๋ฅธ์ชฝ์—์„œ ์™ผ์ชฝ์œผ๋กœ ์ˆœํšŒํ•˜๋ฉฐ `right` ๊ฐ’์„ ์ด์šฉํ•ด ์ ‘๋ฏธ ๊ธฐ์ค€ idx ์ดํ›„์˜ ๊ฐ’๋“ค์„ ๊ณ„์‚ฐ ํžˆ์•ผ `result`์— ๊ณฑํ•จ.
* 4. ๊ฒฐ๊ณผ ๋ฐฐ์—ด `result`๋ฅผ ๋ฐ˜ํ™˜.
*
* ์‹œ๊ฐ„ ๋ณต์žก๋„:
* - ์™ผ์ชฝ์—์„œ ์˜ค๋ฅธ์ชฝ ์ˆœํšŒ: O(n)
* - ์˜ค๋ฅธ์ชฝ์—์„œ ์™ผ์ชฝ ์ˆœํšŒ: O(n)
* - ์ „์ฒด ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
*
* ๊ณต๊ฐ„ ๋ณต์žก๋„:
* - ์ถ”๊ฐ€ ๋ฐฐ์—ด ์—†์ด ์ƒ์ˆ˜ ๊ณต๊ฐ„ ์‚ฌ์šฉ (result๋Š” ๋ฌธ์ œ์˜ ์š”๊ตฌ ์กฐ๊ฑด์— ํฌํ•จ๋˜์ง€ ์•Š์Œ).
* - ์ „์ฒด ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
*/
function productExceptSelf(nums: number[]): number[] {
const numLength = nums.length;
const result = new Array(numLength).fill(1);

let left = 1;
for (let i = 0; i < numLength; i++) {
result[i] *= left;
left *= nums[i];
}

let right = 1;
for (let i = numLength; i >= 0; i--) {
result[i] *= right;
right *= nums[i];
}

return result;
}

0 comments on commit e1d144d

Please sign in to comment.