当前位置:网站首页>2130. maximum twin sum of linked list

2130. maximum twin sum of linked list

2022-06-11 08:56:00 Drag is me

leetcode Force button to brush questions and punch in

* subject :2130. The largest twins in the linked list are
describe : In a size of n And n by even numbers In the linked list , about 0 <= i <= (n / 2) - 1 Of i , The first i Nodes ( Subscript from 0 Start ) The twin node of is (n-1-i) Nodes .

For example ,n = 4 Then the node 0 Is the node 3 Twin nodes of , node 1 Is the node 2 Twin nodes of . This is the length of n = 4 All twin nodes in the linked list .
Twin sum It is defined as the sum of the values of a node and its twin nodes .

Give you the head node of a linked list with an even length head , Please return to the linked list The largest twins and .

Their thinking

1、 The array stores the values of the linked list nodes ;
2、 Compare the maximum twins and ;

Source code ##

class Solution {
    
public:
    int pairSum(ListNode* head) {
    
        vector<int>v;
        while (head) {
    
            v.emplace_back(head->val);
            head = head->next;
        }
        int sum = 0, ans = 0, n = v.size();
        for (int i = 0; i < n / 2; ++i) {
    
            sum = v[i] + v[n - 1 - i];
            ans = max(ans, sum);
        }
        return ans;
    }
};
原网站

版权声明
本文为[Drag is me]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110855010979.html