Leetcode每日一题 —— 2130. 链表最大孪生和

SomeBottle 2026-06-14 09:58 1





思路


首先容易想到的是可以用快慢指针,把链表用一趟扫描截成两半。用栈来存储翻转后的前半段链表然后进行成对求和。


进一步,可以不需要线性额外空间,原地用头插法构造前半段链表翻转后的链表即可。




代码


链栈(常数额外空间):


class Solution {
public:
int pairSum(ListNode* head) {
// 链表节点数为偶数
// 快慢指针找中间点
ListNode *slow=head,*fast=head;
ListNode *rev=nullptr; // 前半段逆转的链表
while(fast!=nullptr){
ListNode* sNext=slow->next;
ListNode* fNext=fast->next;
slow->next=rev; // 头插法构成栈
rev=slow;
slow=sNext;
fast=fNext;
if(fast!=nullptr){
fast=fast->next;
}
}
int res=0;
while(slow!=nullptr){
res=max(res,rev->val+slow->val);
rev=rev->next;
slow=slow->next;
}
return res;
}
};

用了线性额外空间:


class Solution {
public:
int pairSum(ListNode* head) {
// 链表节点数为偶数
// 快慢指针找中间点
ListNode *slow=head,*fast=head;
vector<int> stk;
while(fast!=nullptr){
stk.emplace_back(slow->val);
slow=slow->next;
fast=fast->next;
if(fast!=nullptr){
fast=fast->next;
}
}
int res=0;
while(slow!=nullptr){
res=max(res,stk.back()+slow->val);
stk.pop_back();
slow=slow->next;
}
return res;
}
};
最新回复 (3)
  • YaoHuayong 06-14 10:02
    1

    第一次在l站看到跟算法相关的贴,hhh,古法永远不死 ^-^

  • Lvvvv 06-14 12:08
    2

    脱裤子**的medium^-^


    /**
    * 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:
    int pairSum(ListNode* head) {
    std::deque<int> q;
    while(head != nullptr) {
    q.push_back(head->val);
    head = head->next;
    }
    int res = 0;
    while(!q.empty()) {
    res = max(res,q.front() + q.back());
    q.pop_back();
    q.pop_front();
    }
    return res;
    }
    };
  • CPython 06-14 14:19
    3
    # Definition for singly-linked list.
    # class ListNode:
    # def __init__(self, val=0, next=None):
    # self.val = val
    # self.next = next
    class Solution:
    def pairSum(self, head: Optional[ListNode]) -> int:
    nums1 = []
    n = ans = 0

    while head:
    nums1.append(head.val)
    head = head.next
    n += 1
    for i in range((n >> 1) + 1):
    ans = max(ans, nums1[i] + nums1[n - i - 1])
    return ans

* 帖子来源Linux.do
返回