From f16cc2c982a09c4d86a61a961742d2ddad83458c Mon Sep 17 00:00:00 2001 From: anniemon Date: Sat, 4 Jan 2025 03:35:03 +0900 Subject: [PATCH 1/3] feat: merge two sorted lists --- merge-two-sorted-lists/anniemon.js | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 merge-two-sorted-lists/anniemon.js diff --git a/merge-two-sorted-lists/anniemon.js b/merge-two-sorted-lists/anniemon.js new file mode 100644 index 000000000..38aacc8fe --- /dev/null +++ b/merge-two-sorted-lists/anniemon.js @@ -0,0 +1,39 @@ +/** + * 시간 복잡도: + * list1의 길이가 m, list2의 길이가 n이면 + * 포인터가 최대 m + n만큼 순회하므로 O(m + n) + * 공간 복잡도: + * 포인터를 사용하므로 O(1) + */ +/** + * Definition for singly-linked list. + * function ListNode(val, next) { + * this.val = (val===undefined ? 0 : val) + * this.next = (next===undefined ? null : next) + * } + */ +/** + * @param {ListNode} list1 + * @param {ListNode} list2 + * @return {ListNode} + */ +var mergeTwoLists = function(list1, list2) { + const head = new ListNode(0, null); + let pointer = head; + while(list1 && list2) { + if(list1.val < list2.val) { + pointer.next = list1; + list1 = list1.next; + } else { + pointer.next = list2; + list2 = list2.next; + } + pointer = pointer.next; + } + if(list1) { + pointer.next = list1; + } else { + pointer.next = list2; + } + return head.next; +}; From 4bc2ed946ed86fbe06dd9b15c7091da3b4202b51 Mon Sep 17 00:00:00 2001 From: anniemon Date: Sat, 4 Jan 2025 03:35:11 +0900 Subject: [PATCH 2/3] feat: missing number --- missing-number/anniemon.js | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 missing-number/anniemon.js diff --git a/missing-number/anniemon.js b/missing-number/anniemon.js new file mode 100644 index 000000000..f38f1323f --- /dev/null +++ b/missing-number/anniemon.js @@ -0,0 +1,19 @@ +/** + * 시간 복잡도: nums.length + 1만큼 순회하므로 O(n) + * 공간 복잡도: totalSum, numsSum 변수를 사용하므로 O(1) + */ +/** + * @param {number[]} nums + * @return {number} + */ +var missingNumber = function(nums) { + let totalSum = 0; + for(let i = 0; i <= nums.length; i++) { + totalSum += i; + } + let numsSum = 0; + for(const n of nums) { + numsSum += n; + } + return totalSum - numsSum; +}; From 50b69f5e9be2d3011affb0cfdf10d397966d5a79 Mon Sep 17 00:00:00 2001 From: Seojung Noh <73627443+anniemon@users.noreply.github.com> Date: Sat, 4 Jan 2025 10:04:07 +0900 Subject: [PATCH 3/3] refactor: solve mathematically Co-authored-by: Dongyeong Chon --- missing-number/anniemon.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/missing-number/anniemon.js b/missing-number/anniemon.js index f38f1323f..5700e6746 100644 --- a/missing-number/anniemon.js +++ b/missing-number/anniemon.js @@ -7,10 +7,8 @@ * @return {number} */ var missingNumber = function(nums) { - let totalSum = 0; - for(let i = 0; i <= nums.length; i++) { - totalSum += i; - } + const n = nums.length; + const totalSum = n * (n + 1) / 2; let numsSum = 0; for(const n of nums) { numsSum += n;