베어_
TechBear
베어_
전체 방문자
오늘
어제
  • 분류 전체보기 (336)
    • Spring (33)
      • 개념 (13)
      • Security (5)
      • 실습 (1)
      • 토비 스프링 (11)
    • JPA (6)
    • 프로젝트 기록 (24)
    • DB (13)
    • JAVA (18)
    • 알고리즘 (50)
      • 유형정리 (8)
      • Baekjoon (21)
      • LeetCode (18)
    • 디자인패턴 (0)
    • 개발서적 (79)
      • Effective Java (78)
      • 객체지향의 사실과 오해 (1)
    • 독후감 (4)
    • 보안 (2)
    • 운영체제(OS) (53)
      • 공룡책 (53)
    • 컴퓨터 네트워크 (28)
      • 컴퓨터 네트워크 하향식 접근 (23)
    • 자료구조 (1)
    • DevOps (2)
    • 앱 개발 (20)
      • 안드로이드 스튜디오 (20)

블로그 메뉴

    공지사항

    인기 글

    태그

    • 백준
    • 운영체제
    • 데이터베이스
    • 함수형인터페이스
    • BFS
    • 이펙티브자바
    • jpa
    • Spring
    • C++
    • 자바8
    • 토비스프링
    • dfs
    • 스레드
    • leetcode
    • 스프링시큐리티
    • java
    • 스프링
    • 자바
    • 코드업
    • 알고리즘

    최근 댓글

    최근 글

    티스토리

    hELLO · Designed By 정상우.
    베어_

    TechBear

    알고리즘/LeetCode

    [LeetCode] Merge k Sorted Lists (Java)

    2023. 7. 29. 03:43

    ✉️문제

    https://leetcode.com/problems/merge-k-sorted-lists/description/

     

    Merge k Sorted Lists - LeetCode

    Can you solve this real interview question? Merge k Sorted Lists - You are given an array of k linked-lists lists, each linked-list is sorted in ascending order. Merge all the linked-lists into one sorted linked-list and return it.   Example 1: Input: lis

    leetcode.com

     

    🗝 문제풀이

    1. Collection과 Collection.sort를 이용한 풀이

    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            List<ListNode> nodes = new ArrayList<>();
            for(ListNode node : lists) {
                while(node != null) {
                    nodes.add(node);
                    node = node.next;
                }
            }
    
            Collections.sort(nodes, (a, b) -> a.val - b.val);
            ListNode root = new ListNode();
            ListNode prev = root;
            for(ListNode n : nodes) {
                root.next = n;
                root = n;
            }
    
            return prev.next;
        }
    }

     

    2. 합병정렬을 이용한 풀이

    class Solution {
        public ListNode mergeKLists(ListNode[] lists) {
            if(lists == null || lists.length == 0) return null;
            return mergeHelper(lists, 0, lists.length - 1);
        }
    
        public ListNode mergeHelper(ListNode[] lists, int start, int end) {
            if(start == end) return lists[start];
            int mid = (start + end) / 2;
            ListNode left = mergeHelper(lists, start, mid);
            ListNode right = mergeHelper(lists, mid + 1, end);
            return merge(left, right);
        }
    
        public ListNode merge(ListNode l1, ListNode l2) {
            ListNode tmp = new ListNode();
            ListNode ans = tmp;
    
            while(l1 != null && l2 != null) {
                if(l1.val < l2.val) {
                    tmp.next = l1;
                    l1 = l1.next;
                } else {
                    tmp.next = l2;
                    l2 = l2.next;
                }
                tmp = tmp.next;
            }
    
            tmp.next = l1 == null ? l2 : l1;
            return ans.next;
        }
    }
    저작자표시 비영리 변경금지 (새창열림)
      '알고리즘/LeetCode' 카테고리의 다른 글
      • [LeetCode] Remove Nth Node From End of List (Java)
      • [LeetCode] Longest Consecutive Sequence (Java)
      • [LeetCode] Longest Consecutive Sequence (Java)
      • [LeetCode] Course Schedule (Java)
      베어_
      베어_
      Today I learned | 문제를 해결하는 개발자

      티스토리툴바