-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add post '(Leetcode) 21 - Merge Two Sorted Lists'
- Loading branch information
1 parent
72756e0
commit 727437f
Showing
1 changed file
with
74 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,74 @@ | ||
--- | ||
layout: post | ||
title: (Leetcode) 21 - Merge Two Sorted Lists | ||
categories: [스터디-알고리즘] | ||
tags: | ||
[ | ||
자바, | ||
java, | ||
linked list, | ||
연결 리스트, | ||
리트코드, | ||
Leetcode, | ||
알고리즘, | ||
algorithm, | ||
neetcode, | ||
] | ||
date: 2024-04-29 13:50:00 +0900 | ||
toc: true | ||
--- | ||
|
||
기회가 되어 [달레님의 스터디](https://github.com/DaleStudy/leetcode-study)에 참여하여 시간이 될 때마다 한문제씩 풀어보고 있다. | ||
|
||
[https://neetcode.io/practice](https://neetcode.io/practice) | ||
|
||
--- | ||
|
||
2주간 미션이 나와서 다시 풀기 시작하였다. | ||
|
||
[https://leetcode.com/problems/merge-two-sorted-lists/description/](https://leetcode.com/problems/merge-two-sorted-lists/description/) | ||
|
||
## 내가 작성한 풀이 | ||
|
||
두 리스트에서 작은 값을 찾고 작은 값을 새 ListNode에 추가한 뒤 기존의 리스트에서는 지워준다. | ||
|
||
```java | ||
class Solution { | ||
public ListNode mergeTwoLists(ListNode list1, ListNode list2) { | ||
ListNode head = null; | ||
ListNode tail = null; | ||
|
||
while(!(list1 == null && list2 == null)) { | ||
ListNode selected; | ||
if (list1 == null) { | ||
selected = list2; | ||
list2 = list2.next; | ||
} else if (list2 == null) { | ||
selected = list1; | ||
list1 = list1.next; | ||
} else if (list1.val < list2.val) { | ||
selected = list1; | ||
list1 = list1.next; | ||
} else { | ||
selected = list2; | ||
list2 = list2.next; | ||
} | ||
|
||
ListNode newNode = new ListNode(selected.val); | ||
if(head == null) { | ||
head = newNode; | ||
} else { | ||
tail.next = newNode; | ||
} | ||
|
||
tail = newNode; | ||
} | ||
|
||
return head; | ||
} | ||
} | ||
``` | ||
|
||
### TC, SC | ||
|
||
시간 복잡도는 O(n)이고, 공간 복잡도는 O(n)이다. |