Skip to content

Commit f3e755e

Browse files
committed
add 2130. 链表最大孪生和
1 parent 8fa364b commit f3e755e

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// LeetCode 原题:2130. 链表最大孪生和
2+
// https://leetcode-cn.com/problems/maximum-twin-sum-of-a-linked-list/
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* function ListNode(val, next) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
*/
11+
/**
12+
* 时间复杂度 O(n) 需要遍历两次,一次 n,一次 n/2
13+
* 空间复杂度 O(n) 需要一个长度为 n 的 values 数组保存节点值
14+
* @param {ListNode} head
15+
* @return {number}
16+
*/
17+
var pairSum = function (head) {
18+
// 保存所有节点值
19+
const values = [];
20+
let node = head;
21+
while (node) {
22+
values.push(node.val);
23+
node = node.next;
24+
}
25+
26+
let max = 0;
27+
// 双指针
28+
let left = 0;
29+
let right = values.length - 1;
30+
while (left < right) {
31+
// 维护最大孪生和
32+
max = Math.max(max, values[left++] + values[right--]);
33+
}
34+
35+
return max;
36+
};
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// LeetCode 原题:2130. 链表最大孪生和
2+
// https://leetcode-cn.com/problems/maximum-twin-sum-of-a-linked-list/
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* function ListNode(val, next) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
*/
11+
/**
12+
* @param {ListNode} head
13+
* @return {number}
14+
*/
15+
var pairSum = function (head) {
16+
let slow = head;
17+
let fast = head;
18+
// while 终止时slow将刚好在前半部分的末尾节点
19+
while (fast.next && fast.next.next) {
20+
// 慢指针走一步,快指针走两步
21+
slow = slow.next;
22+
fast = fast.next.next;
23+
}
24+
25+
// 反转后面一半链表,如[1, 2, 3, 4, 5, 6] -> [1, 2, 3, 6, 5, 4]
26+
let last = slow.next;
27+
let cur;
28+
while (last.next) {
29+
cur = last.next;
30+
last.next = cur.next;
31+
cur.next = slow.next;
32+
slow.next = cur;
33+
}
34+
35+
let max = 0;
36+
// 分别从头节点和被反转过的后半部分第一个节点开始,计算最大孪生和
37+
let p = head;
38+
let q = slow.next;
39+
while (q) {
40+
max = Math.max(max, p.val + q.val);
41+
p = p.next;
42+
q = q.next;
43+
}
44+
45+
return max;
46+
};

0 commit comments

Comments
 (0)