문제
문제 링크 : Merge Two Sorted Lists
풀이
/**
* 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) {
let List = new ListNode(0);
let head = List;
let sortedArr = []
while(list1 !== null || list2 !== null){
if(list1 !== null) {
sortedArr.push(list1.val)
list1 = list1.next
}
if(list2 !== null ) {
sortedArr.push(list2.val)
list2 = list2.next
}
}
sortedArr.sort( (a,b) => (a-b) )
for(let i=0; i<sortedArr.length; i++){
head.next = new ListNode(sortedArr[i])
head = head.next
}
return List.next
};
- list1과 list2를 while문을 통해 sortedArr에 val를 담고
- sortedArr에서 sort를 한 후에, List에 다시 담는 과정
- Runtime 57 ms, Memory 44.4 MB
다른 풀이
/**
* 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(a, b) {
var c = root = {val:0, next:null}
while (true) {
if (a===null) {c.next=b; return root.next}
if (b===null) {c.next=a; return root.next}
if (a.val < b.val) {c=c.next=a; a=a.next}
else {c=c.next=b; b=b.next}
}
};
- while문 안에서 list1의 val과 list2의 val을 비교하여 sort
- list1이나 list2나 null이 되면 나머지 next를 그대로 이어서 return
- Runtime 54 ms, Memory 44.2 MB
'알고리즘 풀이 > leetcode' 카테고리의 다른 글
[leetcode, JS] 27. Remove Element (0) | 2023.09.25 |
---|---|
[leetcode, JS] 26. Remove Duplicates from Sorted Array (0) | 2023.09.22 |
[leetcode, JS] 20. Valid Parentheses (0) | 2023.09.22 |
[leetcode, JS] 14. Longest Common Prefix (0) | 2023.09.21 |
[leetcode, JS] 13. Roman to Integer (0) | 2023.09.21 |