跳到主要內容

[Leetcode] 21. Merge Two Sorted Lists

題目

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

看完題目, 以為可以用 LinkedList 這類的東西, 想說 ez ...
結果下面給的 hint Sample 根本就不是那麼一回事啊, 抓頭抓抓抓...


/**
 * Definition for singly-linked list.
 *
 */
public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

先拿到測試資料


/**
 * Created by jerry on 2017/9/24.
 *
 * Merge two sorted linked lists and return it as a new list.
 * The new list should be made by splicing together the nodes of the first two lists.
 */
public class LeetCode21MergeTwoSortedListsTest {

    private LeetCode21MergeTwoSortedLists sol = new LeetCode21MergeTwoSortedLists();

    @Test
    public void test1() {
        final ListNode l1 = null;
        final ListNode l2 = new ListNode(0);

        ListNode act = sol.mergeTwoLists(l1, l2);

        Assert.assertEquals(0, act.val);
    }

    @Test
    public void test2() {
        final ListNode l1 = new ListNode(2);
        final ListNode l2 = new ListNode(1);

        ListNode act = sol.mergeTwoLists(l1, l2);

        Assert.assertEquals(1, act.val);
        Assert.assertEquals(2, act.next.val);
    }

    @Test
    public void test3() {
        final ListNode l1 = new ListNode(1);
        final ListNode l2 = new ListNode(2);

        ListNode act = sol.mergeTwoLists(l1, l2);

        Assert.assertEquals(1, act.val);
        Assert.assertEquals(2, act.next.val);
    }

    @Test
    public void test4() {
        final ListNode l1 = new ListNode(5);
        final ListNode l2 = new ListNode(1);
        final ListNode l3 = new ListNode(2);
        final ListNode l4 = new ListNode(4);
        l2.next = l3;
        l3.next = l4;

        ListNode act = sol.mergeTwoLists(l1, l2);
        Assert.assertEquals(1, act.val);
        Assert.assertEquals(2, act.next.val);
        Assert.assertEquals(4, act.next.next.val);
        Assert.assertEquals(5, act.next.next.next.val);
    }

    @Test
    public void test5() {
        final ListNode l1 = new ListNode(-9);
        final ListNode l2 = new ListNode(3);
        l1.next = l2;

        final ListNode l3 = new ListNode(5);
        final ListNode l4 = new ListNode(7);
        l3.next = l4;

        ListNode act = sol.mergeTwoLists(l1, l3);

        Assert.assertEquals(-9, act.val);
        Assert.assertEquals(3, act.next.val);
        Assert.assertEquals(5, act.next.next.val);
        Assert.assertEquals(7, act.next.next.next.val);
    }
}

Solution

還是抓不太到這種遞迴的解法, 有種輾轉互相比較的意味


public class LeetCode21MergeTwoSortedLists {
    // [-9, 3], [5, 7]
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (Objects.isNull(l1)) return l2;
        if (Objects.isNull(l2)) return l1;

        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l2, l1.next);
            return l1;

        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }
}

留言

這個網誌中的熱門文章

Parse URI query string to Key Value

Parse URI query String to Map 做 urlDecode 處理 沒有任何 query String 回傳 Empty Map 確保只處理 key-value 結構的 query String package com.example.util; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.utils.URIBuilder; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLDecoder; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; /** * Created by jerry on 2017/12/28. * * @author jerry */ @Slf4j public class UriUtil { private UriUtil() { } public static Map splitQuery(final String uri) { Map queryPairs = new LinkedHashMap (); try { final URI uri = new URIBuilder(uri).build(); final String rawQuery = uri.getRawQuery(); log.info("CurrentUrl Query: {}", rawQuery); // 過濾沒有 query string // 還有過濾無法成對 keyValue 的 query, e.g. http://host/path?123 if (Objects.isNull(rawQuery) |...

Google Compute Engine‎ - AccessDeniedExceptions 403

原因 打算從 instance 打包 logs 到 google cloud storage 發生了 AccessDeniedException: 403 Insufficient OAuth2 scope to perform this operation. , 看起來是 instance 沒有 storage 權限 解決 Reference: https://cloud.google.com/compute/docs/access/create-enable-service-accounts-for-instances#changeserviceaccountandscopes 重新設定 service account 權限 instance 上內建有 gcloud , 就直接用現有的工具查詢一下 instance 的 account. $ gsutil info 或者在本機直接 gcloud compute instances describe INSTANCE_NAMES Account: [alpha-number-compute@developer.gserviceaccount.com] Project: [our-project-name] 會看到 instance 的一些狀態, 接下來就簡單多了, 按照下列的說明, 要先 stop instance, 更改 storage scope 再重新 start 。 To change an instance's service account and access scopes, the instance must be temporarily stopped. To stop your instance, read the documentation for Stopping an instance. After changing the service account or access scopes, remember to restart the instance. # Stop Instance gcloud compute instances stop INSTANCE_NAMES # 設定 storage scope 為 full (Read, Write) gcloud co...

Spring-boot Thymeleaf Html5 SAXParseException 解析錯誤

thymeleaf 解析 html5 出錯 <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>SB Admin - Start Bootstrap Template</title> <!-- Bootstrap core CSS--> <link href="../static/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template--> <link href="../static/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- Page level plugin CSS--> <link href="../static/vendor/datatables/dataTables.bootstrap4.css" rel="stylesheet"> <!-- Custom styles for this template--> <li...