Algorithm Study - 002

2021. 6. 2. 18:53·Algorithm/JAVA

Problem


https://leetcode.com/problems/merge-two-sorted-lists/

 

 

Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.

 

Example 1:

 

singly-linked list에 관한 문제이다.

단순 연결 리스트 두 개를 오름차순으로 merge하는 것인데 재귀함수가 떠오른다면 성공.

 

Solution


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        ListNode result;
         
        if(l1.val <= l2.val) {
            result = l1;
            l1.next = mergeTwoLists(l1.next, l2);
        }
        else {
            result = l2;
            l2.next = mergeTwoLists(l1, l2.next);;
             
        }
         
        return result;

    }
}

재귀함수를 이용한 비교방법.

linked-list에 대한 기본적인 지식이 없어 문제를 풀 생각조차 하지 못했다.

 

  • Constraints:
    • The number of nodes in both lists is in the range [0, 50].
    • -100 <= Node.val <= 100
    • Both l1 and l2 are sorted in non-decreasing order.

제약 조건은 위와 같았지만 리스트에 대한 개념이 없었기에 의미는 없었다.

 

Learn Point


1. ListNode에 대한 지식 부족

2. 소스 중 if(l1 == null) return l2; if(l2 == null) return l1; 을 아직도 이해 못하고 있음.

'Algorithm > JAVA' 카테고리의 다른 글

Algorithm Study - 003  (0) 2021.06.03
Algorithm Study - 001  (0) 2021.06.02
숫자 반전 알고리즘  (0) 2021.06.02
'Algorithm/JAVA' 카테고리의 다른 글
  • Algorithm Study - 003
  • Algorithm Study - 001
  • 숫자 반전 알고리즘
seowooJeong
seowooJeong
  • seowooJeong
    개발일기
    seowooJeong
  • 전체
    오늘
    어제
    • 분류 전체보기 (25)
      • FrontEnd (6)
      • BackEnd (6)
      • Project (6)
      • Algorithm (4)
        • JAVA (4)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • React
    • Spring
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    숫자 거꾸로
    intellij querydsl
    gitlab ci/cd
    jenkinsfile
    mybatis list
    jenkins gitlab
    숫자 반전
    querydsl 환경설정
    jeknins 파이프라인
    jQuery
    jenkinsfile 설정
    Java
    collection 리스트
    resultmap 중첩
    QueryDSL 오류
    Spring QueryDsl
    숫자 알고리즘
    resultmap 리스트
    build.gradle querydsl
    spring msa cicd
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
seowooJeong
Algorithm Study - 002
상단으로

티스토리툴바