-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: solve #239 Product of Array Except Self with ts
- Loading branch information
Showing
1 changed file
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |