LeetCode Hot 100:链表

力扣hot100第31题:K个一组翻转链表 给你链表的头节点head,每k个节点一组进行翻转,请你返回修改后的链表。k是一个正整数,它的值小于或等于链表的长度。如果节点总数不是k的整数倍,那么请将最后剩余的节点保持原有顺序。你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。你可以设计一个只用O(1)额外内存空间的算法解决此问题吗? 阅读详情

LeetCode Hot 100:链表

160. 相交链表

思路 1:双指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
        if (headA == nullptr || headB == nullptr)
            return nullptr;

        ListNode* pA = headA;
        ListNode* pB = headB;

        while (pA != pB) {
            pA = pA == nullptr ? headB : pA->next;
            pB = pB == nullptr ? headA : pB->next;
        }

        return pA;
    }
};

思路 2:哈希集合

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
        unordered_set<ListNode*> visited;
        ListNode* p = headA;
        while (p) {
            visited.insert(p);
            p = p->next;
        }

        p = headB;
        while (p) {
            if (visited.count(p))
                return p;
            p = p->next;
        }

        return nullptr;
    }
};

206. 反转链表

思路 1:迭代

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = nullptr;
        ListNode* cur = head;
        ListNode* nxt = nullptr;

        while (cur) {
            nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
        }

        return pre;
    }
};

思路 2:递归

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;
        ListNode* newHead = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr; // 如果忽略了这一点,链表中可能会产生环
        return newHead;
    }
};

思路 3:辅助数组

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* p = head;
        vector<int> arr;
        while (p) {
            arr.push_back(p->val);
            p = p->next;
        }
        int i = arr.size() - 1;
        p = head;
        while (p) {
            p->val = arr[i];
            i--;
            p = p->next;
        }
        return head;
    }
};

234. 回文链表

思路 1:辅助数组 + 双指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> arr;
        ListNode* p = head;
        while (p) {
            arr.push_back(p->val);
            p = p->next;
        }

        int i = 0, j = arr.size() - 1;
        while (i <= j) {
            if (arr[i] != arr[j])
                return false;
            i++;
            j--;
        }

        return true;
    }
};

思路 2:寻找中间节点 + 反转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        ListNode* mid = middleNode(head);
        ListNode* head2 = reverseList(mid);
        while (head2) {
            if (head->val != head2->val)
                return false;
            head = head->next;
            head2 = head2->next;
        }
        return true;
    }
    // 876. 链表的中间结点
    ListNode* middleNode(ListNode* head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
    // 206. 反转链表
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = nullptr, *cur = head;
        while (cur) {
            ListNode* nxt = cur->next;
            cur->next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
};

141. 环形链表

思路 1:快慢指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return false;

        ListNode* slow = head;
        ListNode* fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast)
                break;
        }

        return slow == fast;
    }
};

思路 2:哈希集合

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode* head) {
        unordered_set<ListNode*> hashSet;
        ListNode* p = head;
        while (p) {
            if (hashSet.find(p) != hashSet.end())
                return true;
            hashSet.insert(p);
            p = p->next;
        }

        return false;
    }
};

142. 环形链表 II

思路 1:哈希集合

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        unordered_set<ListNode*> hashSet;
        ListNode* p = head;
        while (p) {
            if (hashSet.find(p) != hashSet.end())
                return p;
            hashSet.insert(p);
            p = p->next;
        }

        return nullptr;
    }
};

思路 2:快慢指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* detectCycle(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return nullptr;

        ListNode* slow = head;
        ListNode* fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                ListNode* p = head;
                while (p != slow) {
                    p = p->next;
                    slow = slow->next;
                }
                return p;
            }
        }

        return nullptr;
    }
};

21. 合并两个有序链表

思路 1:双指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if (list1 == nullptr)
            return list2;
        if (list2 == nullptr)
            return list1;

        ListNode *p1 = list1, *p2 = list2;
        ListNode* dummy = new ListNode();
        ListNode* p = dummy;

        while (p1 && p2) {
            if (p1->val < p2->val) {
                p->next = p1;
                p1 = p1->next;
            } else {
                p->next = p2;
                p2 = p2->next;
            }
            p = p->next;
        }

        if (p1)
            p->next = p1;
        if (p2)
            p->next = p2;

        return dummy->next;
    }
};

思路 2:递归

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if (list1 == nullptr)
            return list2;
        if (list2 == nullptr)
            return list1;

        if (list1->val < list2->val) {
            list1->next = mergeTwoLists(list1->next, list2);
            return list1;
        } else {
            list2->next = mergeTwoLists(list1, list2->next);
            return list2;
        }
    }
};

2. 两数相加

思路 1:迭代

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode();
        ListNode* cur = dummy;
        int add = 0; // 进位

        while (l1 || l2 || add) {
            int d1 = l1 ? l1->val : 0;
            int d2 = l2 ? l2->val : 0;
            int sum = d1 + d2 + add;
            ListNode* nxt = new ListNode(sum % 10);
            cur->next = nxt;
            cur = nxt;
            add = sum / 10;
            if (l1)
                l1 = l1->next;
            if (l2)
                l2 = l2->next;
        }

        return dummy->next;
    }
};

思路 2:模拟

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        num1 = 0
        mult = 1
        while l1:
            num1 += l1.val * mult
            mult *= 10
            l1 = l1.next
        
        num2 = 0
        mult = 1
        while l2:
            num2 += l2.val * mult
            mult *= 10
            l2 = l2.next
        
        sum = num1 + num2
        s = str(sum)
        s = reversed(s)
        
        dummy = ListNode()
        p = dummy
        for i in s:
            p.next = ListNode(int(i))
            p = p.next
        
        return dummy.next

19. 删除链表的倒数第 N 个结点

思路 1:快慢指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy = new ListNode();
        dummy->next = head;
        ListNode* fast = head;
        ListNode* slow = dummy;
        for (int i = 0; i < n; i++)
            fast = fast->next;
        while (fast) {
            fast = fast->next;
            slow = slow->next;
        }
        // slow->next 就是要删除的节点
        ListNode* delNode = slow->next;
        slow->next = delNode->next;
        delNode->next = nullptr;
        delete delNode;

        return dummy->next;
    }
};

思路 2:栈

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy = new ListNode();
        dummy->next = head;
        stack<ListNode*> stk;
        ListNode* cur = dummy;
        while (cur) {
            stk.push(cur);
            cur = cur->next;
        }
        for (int i = 0; i < n; i++)
            stk.pop();
        ListNode* prev = stk.top();
        ListNode* delNode = prev->next;
        prev->next = delNode->next;
        delNode->next = nullptr;
        delete delNode;
        return dummy->next;
    }
};

思路 3:计算链表长度

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
private:
    int getListLength(ListNode* head) {
        int len = 0;
        ListNode* p = head;
        while (p) {
            len++;
            p = p->next;
        }
        return len;
    }

public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy = new ListNode();
        dummy->next = head;
        ListNode* p = dummy;
        int len = getListLength(head);
        for (int i = 0; i < len - n; i++)
            p = p->next;
        ListNode* delNode = p->next;
        p->next = delNode->next;
        delNode->next = nullptr;
        delete delNode;
        return dummy->next;
    }
};

24. 两两交换链表中的节点

思路 1:递归

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;

        ListNode* newHead = head->next;
        head->next = swapPairs(newHead->next);
        newHead->next = head;
        return newHead;
    }
};

思路 2:迭代

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;

        ListNode* dummy = new ListNode();
        dummy->next = head;
        ListNode* p = dummy;

        while (p->next && p->next->next) {
            ListNode *n1 = p->next, *n2 = n1->next;
            p->next = n2;
            n1->next = n2->next;
            n2->next = n1;
            p = n1;
        }

        return dummy->next;
    }
};

25. K 个一组翻转链表

思路 1:模拟

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        ListNode* dummy = new ListNode();
        dummy->next = head;
        ListNode* pre = dummy;

        while (head) {
            ListNode* tail = pre;
            for (int i = 0; i < k; i++) {
                tail = tail->next;
                if (tail == nullptr) {
                    // 剩余部分长度不大于 k
                    return dummy->next;
                }
            }
            ListNode* nxt = tail->next;
            pair<ListNode*, ListNode*> p = reverseList(head, tail);
            head = p.first;
            tail = p.second;

            pre->next = head;
            tail->next = nxt;
            pre = tail;
            head = tail->next;
        }

        return dummy->next;
    }
    pair<ListNode*, ListNode*> reverseList(ListNode* head, ListNode* tail) {
        ListNode* prev = tail->next;
        ListNode* p = head;
        while (prev != tail) {
            ListNode* nxt = p->next;
            p->next = prev;
            prev = p;
            p = nxt;
        }
        return {tail, head};
    }
};

138. 随机链表的复制

思路 1:迭代 + 哈希

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
public:
    Node* copyRandomList(Node* head) {
        if (head == nullptr)
            return nullptr;

        Node* curNode = head;
        unordered_map<Node*, Node*> hash; // <原结点,新结点>
        // 复制各节点,建立 “原节点 -> 新节点” 的哈希映射
        while (curNode) {
            hash[curNode] = new Node(curNode->val);
            curNode = curNode->next;
        }
        curNode = head;
        while (curNode) {
            hash[curNode]->next = hash[curNode->next];
            hash[curNode]->random = hash[curNode->random];
            curNode = curNode->next;
        }
        // 返回新链表的头节点
        return hash[head];
    }
};

思路 2:递归 + 哈希

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* next;
    Node* random;

    Node(int _val) {
        val = _val;
        next = NULL;
        random = NULL;
    }
};
*/

class Solution {
private:
    unordered_map<Node*, Node*> hashMap; // <原结点,新结点>
public:
    Node* copyRandomList(Node* head) {
        if (head == nullptr)
            return nullptr;

        if (hashMap.find(head) == hashMap.end()) {
            Node* newHead = new Node(head->val);
            hashMap[head] = newHead;
            newHead->next = copyRandomList(head->next);
            newHead->random = copyRandomList(head->random);
        }

        return hashMap[head];
    }
};

148. 排序链表

思路 1:辅助数组

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head == nullptr)
            return nullptr;

        ListNode* p = head;
        vector<int> arr;
        while (p) {
            arr.push_back(p->val);
            p = p->next;
        }
        sort(arr.begin(), arr.end());
        p = head;
        for (int i = 0; i < arr.size(); i++) {
            p->val = arr[i];
            p = p->next;
        }
        return head;
    }
};

思路 2:自顶向下归并排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) { return sortList(head, nullptr); }
    // 辅函数 - 给定头尾指针,进行归并排序
    ListNode* sortList(ListNode* head, ListNode* tail) {
        if (head == nullptr)
            return head;
        if (head->next == tail) {
            head->next = nullptr;
            return head;
        }
        ListNode *slow = head, *fast = head;
        while (fast != tail) {
            slow = slow->next;
            fast = fast->next;
            if (fast != tail)
                fast = fast->next;
        }
        ListNode* mid = slow;
        return merge(sortList(head, mid), sortList(mid, tail));
    }
    // 辅函数 - 按升序合并两个链表
    ListNode* merge(ListNode* head1, ListNode* head2) {
        ListNode *dummy = new ListNode();
        ListNode *p = dummy;
        ListNode *p1 = head1, *p2 = head2;
        while (p1 && p2) {
            if (p1->val < p2->val) {
                p->next = p1;
                p1 = p1->next;
            } else {
                p->next = p2;
                p2 = p2->next;
            }
            p = p->next;
        }
        p->next = p1 ? p1 : p2;
        return dummy->next;
    }
};

23. 合并 K 个升序链表

思路 1:优先队列

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
private:
    struct Comp {
        bool operator()(ListNode* l1, ListNode* l2) {
            return l1->val > l2->val;
        }
    };

public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.empty())
            return nullptr;

        priority_queue<ListNode*, vector<ListNode*>, Comp> pq;
        for (ListNode* list : lists)
            if (list != nullptr)
                pq.push(list);

        ListNode* dummy = new ListNode();
        ListNode* p = dummy;
        while (!pq.empty()) {
            p->next = pq.top();
            pq.pop();
            p = p->next;
            if (p->next)
                pq.push(p->next);
        }

        return dummy->next;
    }
};

思路 2:顺序合并

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
private:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if (list1 == nullptr)
            return list2;
        if (list2 == nullptr)
            return list1;

        ListNode* dummy = new ListNode();
        ListNode* p = dummy;
        ListNode *p1 = list1, *p2 = list2;
        while (p1 && p2) {
            if (p1->val < p2->val) {
                p->next = p1;
                p1 = p1->next;
            } else {
                p->next = p2;
                p2 = p2->next;
            }
            p = p->next;
        }
        p->next = p1 ? p1 : p2;

        return dummy->next;
    }

public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        ListNode* ans = nullptr;
        for (size_t i = 0; i < lists.size(); i++)
            ans = mergeTwoLists(ans, lists[i]);
        return ans;
    }
};

思路 3:分治合并

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
private:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        if (list1 == nullptr)
            return list2;
        if (list2 == nullptr)
            return list1;

        ListNode* dummy = new ListNode();
        ListNode* p = dummy;
        ListNode *p1 = list1, *p2 = list2;
        while (p1 && p2) {
            if (p1->val < p2->val) {
                p->next = p1;
                p1 = p1->next;
            } else {
                p->next = p2;
                p2 = p2->next;
            }
            p = p->next;
        }
        p->next = p1 ? p1 : p2;

        return dummy->next;
    }
    ListNode* merge(vector<ListNode*>& lists, int left, int right) {
        if (left == right)
            return lists[left];
        if (left > right)
            return nullptr;
        int mid = left + (right - left) / 2;
        return mergeTwoLists(merge(lists, left, mid),
                             merge(lists, mid + 1, right));
    }

public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        return merge(lists, 0, lists.size() - 1);
    }
};

146. LRU 缓存

思路 1:哈希表 + 链表

class LRUCache {
private:
    int size;
    unordered_map<int, list<pair<int, int>>::iterator> hash;
    list<pair<int, int>> cache; // <key, value>

public:
    LRUCache(int capacity) : size(capacity) {

    }
    
    int get(int key) {
        auto iter = hash.find(key);
        if (iter == hash.end())
            return -1;
        // iter->second 是一个 list<pair<int, int>>::iterator
        cache.splice(cache.begin(), cache, iter->second);
        // iter->second->second 是一个 value
        return iter->second->second;
    }
    
    void put(int key, int value) {
        auto iter = hash.find(key);
        if (iter != hash.end())
        {
            iter->second->second = value;
            cache.splice(cache.begin(), cache, iter->second);
            return;
        }
        cache.insert(cache.begin(), pair<int, int>(key, value));
        hash[key] = cache.begin();
        if (cache.size() > size)
        {
            // cache.back().first 是一个 key
            hash.erase(cache.back().first);
            cache.pop_back();
        }
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */

思路 2:哈希表 + 自定义双向链表

class Node {
public:
    int key, value;
    Node *prev, *next;

    Node(int k = 0, int v = 0) : key(k), value(v) {}
};

class LRUCache {
private:
    int capacity;
    Node* dummy; // 哨兵节点
    unordered_map<int, Node*> key_to_node;

    // 删除一个节点(抽出一本书)
    void remove(Node* x) {
        x->prev->next = x->next;
        x->next->prev = x->prev;
    }

    // 在链表头添加一个节点(把一本书放在最上面)
    void push_front(Node* x) {
        x->prev = dummy;
        x->next = dummy->next;
        x->prev->next = x;
        x->next->prev = x;
    }

    Node* get_node(int key) {
        auto it = key_to_node.find(key);
        if (it == key_to_node.end()) // 没有这本书
            return nullptr;
        auto node = it->second; // 有这本书
        remove(node);           // 把这本书抽出来
        push_front(node);       // 放在最上面
        return node;
    }

public:
    LRUCache(int capacity) : capacity(capacity), dummy(new Node()) {
        dummy->prev = dummy;
        dummy->next = dummy;
    }

    int get(int key) {
        auto node = get_node(key);
        return node ? node->value : -1;
    }

    void put(int key, int value) {
        auto node = get_node(key);
        if (node) {              // 有这本书
            node->value = value; // 更新 value
            return;
        }
        key_to_node[key] = node = new Node(key, value); // 新书
        push_front(node);                               // 放在最上面
        if (key_to_node.size() > capacity) {            // 书太多了
            auto back_node = dummy->prev;
            key_to_node.erase(back_node->key);
            remove(back_node); // 去掉最后一本书
            delete back_node;  // 释放内存
        }
    }
};
力扣hot100第22题:相交链表 的输入如下(你设计的程序。 阅读详情

相关推荐

SAP CO-PA数据传送避坑指南:销售开票与FI/MM记账的日常配置实操(含KEKF/KE4I/KEI2)

本文深入解析SAP CO-PA数据传送中的常见配置问题,特别是销售开票与FI/MM记账环节的实操避坑指南。通过KEKF/KE4I/KEI2等关键配置点的详细说明,帮助用户避免数据失真和重复记录,提升获利能力分析的准确性。文章结合实战案例,揭示官方文档未提及的'数据黑洞'形成机制,为SAP顾问提供实用的排雷手册。

weixin_26905487的博客 390

力扣hot100第33题:排序链表

给你链表的头结点head,请将其按排列并返回。

weixin_74009895的博客 441

利用kettle进行数据库数据比对

Kettle是一款国外开源的ETL工具,纯java编写,可以在Windows、Linux、Unix上运行,数据抽取高效稳定。本人用的版本是6.1。 之前用kettle这个开源的ETL工具是用来做数据抽取的,这次测试有个需求,是做数据库数据的比对。验证源表到目标表的逻辑正确,从而利用源表自己写SQL逻辑,生成的结果和目标表去比对。这次想到了利用kettle的数据比较功能,来做这些数据校验。 ...

多米诺DU的专栏 1万+

力扣hot100第32题:随机链表的复制

给你一个长度为n的链表,每个节点包含一个额外增加的随机指针random,该指针可以指向链表中的任何节点或空节点。构造这个链表的。深拷贝应该正好由n个节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的next指针和random指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。。例如,如果原链表中有X和Y两个节点,其中。那么在复制链表中对应的两个节点x和y,同样有。返回复制链表的头节点。用一个由n个节点组成的链表来表示输入/输出中的链表。

weixin_74009895的博客 733

Android SystemUI——车载CarSystemUI加载(八)

车载 CarSystemUI 是指专门为汽车环境设计的用户界面和用户体验(UI/UX),它通常与 Android Automotive OS 或其他嵌入式操作系统一起工作,为驾驶者和乘客提供安全、直观且高效的交互方式。Android Automotive OS 是 Google 专门为汽车开发的操作系统版本,它基于 Android 平台,并针对车辆内部的使用进行了优化。

小旭的专栏 2174

YOLO26 实战全流程:从数据集标注到端到端无NMS推理(完整版,附ProgLoss核心调参技巧+避坑指南)

本章节是实战经验的精华❌ 数据集标注不规范,导致模型精度低 → ✅ 严格遵守工业级标注规范,标注框紧贴目标边缘,不要漏标/多标;❌ 训练时未使用预训练权重,导致收敛极慢 → ✅ 必须开启,预训练权重能让模型快速收敛;❌ ProgLoss参数调整幅度过大,导致训练崩溃 → ✅ 每次只调整一个参数,幅度±0.02即可,循序渐进;❌ 推理时强行添加NMS参数,画蛇添足 → ✅ YOLO26无需NMS,推理命令中不要加conf/iou参数,否则会降低推理速度;

专注于Python爬虫开发,分享爬虫技巧、项目实战与反爬经验,使用Scrapy、BeautifulSoup等工具,解决数据抓取难题。 1141

hot100:链表倒数k个节点- 力扣(LeetCode)

令 pre , cur 一起走,直到 cur 走过尾节点时跳出,此时 pre 指向「倒数第 k 个节点」,返回之即可;实现一种算法,找出单向链表中倒数第 k 个节点。返回该链表中倒数第k个节点。先令 cur 走 k 步,此时 pre , cur 的距离为 k;说明:返回倒数第2个节点4,系统会打印后面所有的节点来比较。初始化双指针 pre , cur 都指向头节点 head;输入:{1,2,3,4,5},2。

2401_87004385的博客 346

用一套可追溯的闭环,把设备变成可管理的资产:SAP S/4HANA Asset Management 模块详解

摘要:SAP S/4HANA的资产管理模块(EAM)通过标准化流程管理企业资产全生命周期,解决资产状态、需求和资源的不确定性。系统将资产抽象为技术对象,支持纠正性和预防性维护流程,通过维护工单实现可执行的工作包,并与物料管理、财务、生产计划等模块集成形成管理闭环。该模块可帮助降低非计划停机时间,通过数据驱动决策优化维护策略,提升资产可用率和运营效率。(149字)

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 253

力扣hot100 第206题:反转链表

本文介绍了LeetCode热题206反转链表的解法。文章给出了问题描述和三个示例,展示了如何使用Java实现链表反转的简洁代码。解法采用迭代方式,通过维护pre和cur两个指针,逐个反转节点指向,最终返回反转后的链表头节点pre。该方法时间复杂度O(n),空间复杂度O(1),是解决链表反转问题的经典方案。

schizophrenics6的博客 300

基于通义千问2.5-7B-Instruct的技术深度解析

通义千问2.5-7B-Instruct是一个基于Transformer架构的大型语言模型,具有70亿参数。它通过自注意力机制和前馈神经网络处理输入序列,能够捕捉长距离依赖关系,适用于多种NLP任务。微调是指在预训练模型的基础上,使用特定任务的数据进行进一步训练,以使模型更好地适应特定任务。微调可以显著提高模型在特定任务上的性能。通义千问2.5-7B-Instruct是一个强大的语言模型,适用于多种NLP任务。通过深入理解其架构、微调方法和核心代码,可以更好地应用于实际场景。

zhangjiaofa的专栏 1569

YOLO11改进|卷积篇|引入多样化分支块DBB

YOLO11中添加多样化分支块DBB

A1983Z的博客 1446

力扣hot100:反转链表

反转链表的核心思想是通过改变指针的方向来实现链表的反转。使用迭代方式,可以在遍历链表的过程中完成反转操作,避免使用额外的空间。这种方法的时间复杂度是 O(n),空间复杂度是 O(1),是最优解法。

一本大学生java学习技术分享与交流 465

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

LeetCode HOT100刷题笔记(四):链表

ps:笔记和代码按本人理解整理,重思路

学习记录 1239

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

力扣HOT100之链表: 148. 排序链表

会根据键进行升序排序,因此我们将节点的值作为键,其在整个链表中的出现次数作为值,当所有元素统计完毕以后,我们直接按照顺序遍历哈希表,然后将一个键对应的值填入到链表中,当哈希表中所有键都填充完毕时,链表就排序好了,直接返回即可。在手撕面试的时候这样做肯定是不行的,我又去看了下灵神的题解,他的思路也比较简单易懂,但是需要两道题的前置基础,分别是。这道题直接用蠢办法来做的,直接先遍历一遍链表,用一个哈希表统计每个值出现的次数,由于。,这里就不细讲两道题的解题思路了,我们直接将两道题的函数(

weixin_52151595的博客 459

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

LeetCode 热题 HOT 100:链表专题

题目包含:两数相加、删除链表的倒数第 N 个结点、合并两个有序链表、合并 K 个升序链表、环形链表、环形链表 II、排序链表、相交链表、反转链表、回文链表

秀岩的博客 987

LeetCode HOT100刷题笔记(五):链表

ps:笔记和代码按本人理解整理,重思路

学习记录 1106

力扣hot100:相交链表

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。

weixin_45866961的博客 94

力扣HOT100之链表:160. 相交链表

返回即可,如果两条链表相交,那么返回的就是他们真正的交点,如果两个链表没有相交,返回的就是空指针,所以代码写出来特别简洁。上面是两个链表相交的情况,下面是两条链表不相交(可以认为是广义的相交,因为两个链表的末尾都指向空节点)的情况,这道题已经刷过三四回了,看到这道题就直接秒了,纯数学技巧,我们直接用两个指针变量分别保存。的遍历路径用红色数字表示,可以看出,在上面的例子中,总共经过了10步,在下面的例子中,总共经过了9步,链表的首元素地址,继续遍历,同理,当遍历到。链表的首元素地址,并继续遍历,当。

weixin_52151595的博客 364

力扣HOT100之链表:25. K 个一组翻转链表

的第一个节点和最后一个节点的指向关系处理好就行,然后再移动虚拟头节点即可,为下一次局部反转做准备,至于在此后的局部反转中,pre指针初始状态下指向哪里,我们是不关心的,因为在局部反转之后,我们会对反转过后的局部链表的首节点和尾节点的指向进行专门的处理(得益于虚拟头节点的存在),不用担心pre初值的指向带来的隐患。灵神的思路还是很容易理解的,通过一个二重循环来实现k个一组反转链表,外层循环用于控制局部反转的次数,内层循环用于反转局部k个节点,在内层循环中,反转的思路和。,下面简单演示一个节点个数为。

weixin_52151595的博客 525

力扣HOT100之链表:234. 回文链表

想法是美好的,但是我兴冲冲写完提交以后报错了,原因是我调用反转链表函数以后,对原链表的结构也进行了修改,这就导致无法正常比较,然后得到了错误的结果,后面我还是用最笨的办法AC的,就是用一个vector存储链表中的所有值,然后再将其复制到一个新的vector,再将新的vector反转,最后再与原vector逐元素比较,但凡出现不同的元素就直接返回false,否则返回true,但是这样做的时间复杂度和空间复杂度都太高了,无语(ˉ▽ˉ;是否为空,若为空,说明比较结束,否则就还没结束。,所以我们只需要判断。

weixin_52151595的博客 455

力扣HOT100之链表:138. 随机链表的复制

这道题要求将整个链表进行深拷贝,新链表中不包含任何原链表的节点,但是新链表中各个节点存储的值和各个节点的指向关系需要和原链表一模一样。节点)相较于头节点的偏移量,然后我们在新链表中通过这个偏移量找到对应的节点,再将当前遍历到的节点的。指针遍历整个链表,先将新链表的所有节点构造出来,然后再来逐个处理每一个节点的。之前的某个节点,也有可能指向自己,在构造链表的过程中,完全有可能出现。指针进行遍历,因此在构造链表的过程中,我们应当使用。对应的节点还没构造出来的情况,此外,按照。之后的某个节点,也有可能指向。

weixin_52151595的博客 450

力扣HOT100之链表:23. 合并 K 个升序链表

但是这么做的耗时有点太长了,AC之后去看了下灵神的题解,感觉他的第一种思路特别通俗易懂,主要是借用了数据结构本身的特性,利用优先队列进行自动排序,而无需手动排序,因此我们只需要不断地将节点加入到优先队列中即可,这道题需要我们自定义一个排序规则,以对链表节点进行排序,当我们把优先队列的队头元素(队列内的最小值)取出后,我们需要判断队头元素的下一个节点是否为空,若不为空才将下一个节点加入到优先队列中。当所有链表的所有节点都被加入到优先队列中后,我们直接退出循环。循环中,如果遇到了还没遍历到末尾的链表,则。

weixin_52151595的博客 297

力扣HOT100之链表:206. 反转链表

双指针,顾名思义,就是用两个指针来保存一些必要的变量,对于一段链表,我们要将其反转,我们必须知道这段链表的前置节点,当前遍历到的节点和当前节点的下一节点,我们分别用。这道题今天已经是第三次刷了,思路都知道但是代码就是写不对,我真的要红温了🤯🤯。从上面到下面经历了一次反转,可以看到,在一次反转中,我们仅将。的位置整体后移一位,然后周而复始,我们通过一个。节点也是反转后的链表的首元素,因此我们直接返回。以后这道题就统一用双指针法来做吧。循环来实现这样的处理流程,直到。指向原链表的最后一个元素,此时。

weixin_52151595的博客 348

力扣hot100:链表:234.回文链表

111

2401_83606094的博客 275

算法复盘——Leetcode hot100:链表160

160

Xxx's Blog 1197
上一篇: Leetcode 第 419 场周赛题解
下一篇: LeetCode Hot 100:哈希
UestcXiye
博客等级 码龄8年 9030粉丝 1306原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

UestcXiye

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值