阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给定一个偶数长度的链表,下标从 0 开始。 下标 i 和下标 n-1-i 的节点互为孪生节点,计算所有孪生节点值之和,返回其中的最大值。
示例:
输入:head = [5,4,2,1] 输出:6 解释:(5+1)=6,(4+2)=6,最大和为 6。
package lc2130;
import java.util.Deque;
import java.util.LinkedList;
public class Solution {
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;
}
}
public int pairSum(ListNode head) {
Deque<Integer> stack = new LinkedList<>();
while (head != null) {
stack.add(head.val);
head = head.next;
}
int max = Integer.MIN_VALUE;
while (!stack.isEmpty()) {
int a = stack.removeFirst() + stack.removeLast();
max = Math.max(a, max);
}
return max;
}
}/**
* 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 int pairSum(ListNode head) {
// 快慢指针查找链表中点
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 反转后半段链表
ListNode secondHalf = reserve(slow);
int maxSum = 0;
ListNode p1 = head;
ListNode p2 = secondHalf;
// 同步遍历两段链表,计算孪生和并更新最大值
while (p2 != null) {
maxSum = Math.max(maxSum, p1.val + p2.val);
p1 = p1.next;
p2 = p2.next;
}
return maxSum;
}
// 迭代方式反转链表
private ListNode reserve(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}