일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- MySQL
- node.js
- nodeJS
- DP
- JSX
- event
- state
- route
- treenode
- Callback
- priority_queue
- map
- server
- component
- c++
- bit
- Navigation
- Context
- count
- queue
- 비트연산
- axios
- BinaryTree
- array
- leetcode
- Props
- css
- React
- UE5
- routes
- Today
- Total
우사미 코딩
[Leetcode] 148. Sort List 본문
1. 문제링크
Sort List - LeetCode
Can you solve this real interview question? Sort List - Given the head of a linked list, return the list after sorting it in ascending order. Example 1: [https://assets.leetcode.com/uploads/2020/09/14/sort_list_1.jpg] Input: head = [4,2,1,3] Output: [1,
leetcode.com
지맘대로 생긴 ListNode를 오름차순으로 정렬하는 문제
2. Key Point - 제일 미니한 단위로 쪼갠다(재귀호출), merge한다
1) ListNode를 두개로 나눈다 - slow, fast pointers 사용
original = [4,2,3,1] 이라면
slow = [4,2], fast = [3,1]이 되도록 나눈다
이렇게 나눈 것을 재귀 호출하여 나눌 수 있는 가장 작은 2개의 ListNode로 만든다
2) merge 함수 구현 - 오름차순 정렬
나눈 2개의 ListNode를 ascending order로 merge한다
3. solution
class Solution {
public:
ListNode* merge(ListNode* l1, ListNode* l2){
ListNode* dummy = new ListNode(-1);
ListNode* node = dummy;
while(l1 && l2){
if(l1->val <= l2->val){
node->next = new ListNode(l1->val);
l1 = l1->next;
} else {
node->next = new ListNode(l2->val);
l2 = l2->next;
}
node = node->next;
}
if(l1) node->next = l1;
if(l2) node->next = l2;
return dummy->next;
}
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
// find mid
ListNode* slow = head;
ListNode* fast = head;
ListNode* prev = slow;
while(fast && fast->next){
prev = slow;
slow = slow->next;
fast = fast->next->next;
}
prev->next = NULL;
ListNode* l1 = sortList(head);
ListNode* l2 = sortList(slow);
return merge(l1, l2);
}
};
'Leetcode' 카테고리의 다른 글
[Leetcode] 110. Balanced Binary Tree (0) | 2023.05.23 |
---|---|
[Leetcode] 953. Verifying an Alien Dictionary - hash map (0) | 2023.05.22 |
[Leetcode] 48. Rotate Image - Matrix (0) | 2023.05.19 |
[Leetcode] 15. 3Sum - two pointers를 사용하자 (0) | 2023.05.18 |
[Leetcode] 153. Find Minimum in Rotated Sorted Array - 주옥같은 binary search (0) | 2023.05.17 |