본문으로 바로가기

[LeetCode] 148. Sort List - 문제풀이

category 알고리즘/LeetCode 2022. 2. 24. 14:31

Description

주어진 링크드리스트를 오름자순으로 정렬하여 반환하는 문제입니다.

 

Example 1:

Input: head = [4,2,1,3]
Output: [1,2,3,4]

Example 2:

Input: head = [-1,5,3,4,0]
Output: [-1,0,3,4,5]

Example 3:

Input: head = []
Output: []

Constraints:

  • The number of nodes in the list is in the range [0, 5 * 10^4].
  • -10^5 <= Node.val <= 10^5

Follow up: Can you sort the linked list in O(n logn) time and O(1) memory (i.e. constant space)?

Solution 1. 선택 정렬 (Selection Sort)

public ListNode sortList(ListNode head) {
    ListNode dHead = new ListNode(0);
    dHead.next = head;
    ListNode cur = dHead;

    while(cur.next != null){
        ListNode i = cur.next;
        ListNode j = cur.next.next;
        while(j != null){
            if(i.val > j.val){
               int temp = i.val;
                i.val = j.val;
               j.val = temp;
            }
            j = j.next;
        }
        cur = cur.next;
    }
    return dHead.next;
}

선택정렬을 이용하여 정렬합니다. 이외에도 버블정렬, 삽입 정렬이 사용가능하며 시간복잡도는 모두 O(n^2) 입니다.

Solution 2. 병합정렬 (merge sort)

public ListNode sortList(ListNode head) {
  if (head == null || head.next == null)
      return head;

  // step 1. cut the list to two halves
  ListNode prev = null, slow = head, fast = head;

  while (fast != null && fast.next != null) {
      prev = slow;
      slow = slow.next;
      fast = fast.next.next;
  }

  prev.next = null;

  // step 2. sort each half
  ListNode l1 = sortList(head);
  ListNode l2 = sortList(slow);

  // step 3. merge l1 and l2
  return merge(l1, l2);
}

ListNode merge(ListNode l1, ListNode l2) {
  ListNode l = new ListNode(0), p = l;

  while (l1 != null && l2 != null) {
      if (l1.val < l2.val) {
          p.next = l1;
          l1 = l1.next;
      } else {
          p.next = l2;
          l2 = l2.next;
      }
      p = p.next;
  }

  if (l1 != null)
      p.next = l1;

  if (l2 != null)
      p.next = l2;

  return l.next;
}

병합정렬 알고리즘을 이용하여 시간복잡도를 O(n Log n) 으로 줄일 수 있습니다

Reference

 

Sort List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com