【链表】2130.链表最大孪生和

【链表】2130.链表最大孪生和

解题思路

 孪生和的定义是从前往后数和从后往前位置相同的数之和,现在要求找出其中的最大值,最容易想到的做法是使用数组储存链表中的数,然后两个指针从两端开始向中间遍历,在过程中计算孪生和并且更新答案。

/**
 * 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) {
    
    
        if(head == null){
    
    
            return 0;
        }

        if(head.next == null){
    
    
            return head.val;
        }

        // 定义前后指针
        // 使用数组 存储最大值
        // 两个指针从两端开始向中间进行遍历  在过程中计算暖省和 并且更新答案
        // int[] nums = new int[100000];

        ListNode first = head;
 
        int count = 0;
        // second指向链表的末尾
        while(first != null)
        {
    
       
            count++;// 计算链表的长度
            first = first.next;
        }

        int[] nums = new int[count];
        // 将链表中的所有数全部存储到链表中
        first = head;

        for(int i = 0; i < count; i++){
    
    
            nums[i] = first.val;
            first = first.next;
        }

        int max = 0;
        int len = count - 1;
        // 链表数目为偶数
        for(int j = 0; j <= (nums.length - 1) / 2; j++){
    
    
            if(nums[j] + nums[len] > max){
    
    
                max = nums[j] + nums[len];
            }
            len--;
        }

        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44653420/article/details/131738914