Leetcode 2. Add Two Numbers

本文详细解析了LeetCode上的链表加法问题,通过设置进位位,实现了两链表数值的相加。代码示例使用Java实现,展示了链表操作的简洁方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:给定两个链表,返回链表相加的结果,head是个位数,链位是高位。

题目链接:Leetcode 2. Add Two Numbers

链表的操作真的很简单了,按照外部排的思想,设置carrier位,看是否需要进位,然后逐位相加,看是否需要进位。

代码如下

import java.util.Arrays;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2];
        int[] numNew = new int[nums.length];
        System.arraycopy(nums, 0, numNew, 0, nums.length);
        Arrays.sort(numNew);
        int l = 0;
        int r = nums.length - 1;
        int currSum;
        while (l < r) {
            currSum = numNew[l] + numNew[r];
            if (currSum < target) {
                l++;
            } else if (currSum > target) {
                r--;
            } else {
                boolean flag = true; 
                for (int i = 0; i < nums.length; i++) {
                    if ((nums[i] == numNew[l] || nums[i] == numNew[r]) && flag==true) {

                        ans[0] = i;  //左边index
                        flag = false;
                    } else if ((nums[i] == numNew[r] || nums[i] == numNew[l]) && flag==false) {
                        ans[1] = i; // 右边
                    }
                }
                return ans;
            }
        }
        return null;
    }
}

参考链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值