Skip to content
Rain Hu's Workspace
Go back

[Algo] 3-1. Two Pointer/Sliding Window

Rain Hu

前言:
先前我們在鏈表的單元已經介紹過求鏈表中點的「前後指針」與求有環鏈表的「快慢指針」,這都是雙指針的應用。
在接下來的這個章節,主要會介紹的雙指針應用,與更進階的滑動窗口(sliding window)的應用。

一、Two Pointer in LinkedList

1. Merge Two Sorted Lists

ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
    ListNode* dummy = new ListNode();
    ListNode* curr = dummy;
    while (list1 && list2) {
        if (list1->val <= list2->val) {
            curr->next = list1;
            list1 = list1->next;
        } else {
            curr->next = list2;
            list2 = list2->next;
        }
        curr = curr->next;
    }
    if (list1) curr->next = list1;
    if (list2) curr->next = list2;
    return dummy->next;
}

二、Two Pointer in Array

三、Sliding Window



Share this post on:

Previous
[Algo] 3-10. Binary Indexed Tree(Fenwick Tree, BIT)
Next
[LeetCode] 132. Palindrome Partitioning II