|
| 1 | +/** |
| 2 | + * @description |
| 3 | + * time complexity: O(n^2) |
| 4 | + * space complexity: O(1) |
| 5 | + * ํ์ด ๋ฐฉ๋ฒ: |
| 6 | + * ์นด์ดํฐ๋ฅผ ํตํด ๋ฐ๋ณต๋ฌธ ๋๊ธฐ |
| 7 | + * ๊ฒ์ผ๋ก๋ ๋ฐ๋ณต๋ฌธ์ด ํ๊ฐ ๊ฐ์๋ณด์ด์ง๋ง ์ด์ค๋ฐ๋ณต๋ฌธ์ด๋ค. |
| 8 | + * @param {number[]} nums |
| 9 | + * @param {number} target |
| 10 | + * @return {number[]} |
| 11 | + */ |
| 12 | +const twoSumSoluton1 = function (nums, target) { |
| 13 | + let left = 0; |
| 14 | + let right = 1; |
| 15 | + while (left < nums.length - 1) { |
| 16 | + const sum = nums[left] + nums[right]; |
| 17 | + if (sum === target) { |
| 18 | + return [left, right]; |
| 19 | + } |
| 20 | + |
| 21 | + if (right < nums.length - 1) { |
| 22 | + right += 1; |
| 23 | + } else { |
| 24 | + left += 1; |
| 25 | + right = left + 1; |
| 26 | + } |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +/** |
| 31 | + * @description |
| 32 | + * ๋ค๋ฅธ ์ฌ๋๋ค์ ํ์ด๋ฅผ ๋ณด๊ณ ๊ฐ์ ํ ์๋ฃจ์
|
| 33 | + * time complexity: O(n) |
| 34 | + * space complexity: O(n) |
| 35 | + * ํ์ด ๋ฐฉ๋ฒ: |
| 36 | + * ์ด์ ๊ฐ๋ค ์ค์ ์ํ๋ ๊ฐ์ด ์๋์ง๋ง ํ์ธ ํ ์ถ์ถ, ์๊ฐ๋ณต์ก๋๋ฅผ ํฌ๊ฒ ๊ฐ์์ํด |
| 37 | + * ํ์ง๋ง ํด์ฌ๋งต์ ๋ง๋ค์ด์ผํด์ ๊ณต๊ฐ๋ณต์ก๋๋ O(n)์ผ๋ก ๋ณ๊ฒฝ |
| 38 | + * @param {number[]} nums |
| 39 | + * @param {number} target |
| 40 | + * @return {number[]} |
| 41 | + */ |
| 42 | +const twoSumSoluton2 = function (nums, target) { |
| 43 | + const hashMap = new Map(); |
| 44 | + |
| 45 | + for (let i = 0; i < nums.length; i += 1) { |
| 46 | + const calculatedTarget = target - nums[i]; |
| 47 | + if (hashMap.has(calculatedTarget)) { |
| 48 | + return [i, hashMap.get(calculatedTarget)]; |
| 49 | + } |
| 50 | + |
| 51 | + hashMap.set(nums[i], i); |
| 52 | + } |
| 53 | + |
| 54 | + return []; |
| 55 | +}; |
0 commit comments