力扣刷题-2.两数相加

2.两数相加

给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。

请你将两个数相加,并以相同形式返回一个表示和的链表。

你可以假设除了数字 0 之外,这两个数都不会以 0 开头。

输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 80
输入:l1 = [0], l2 = [0]
输出:[0]
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]

 来源:力扣(LeetCode) 链接:力扣

下面这个案例采用了内部类的方式,可以肆无忌惮的访问或调用ListNote类中的属性或方法

import java.util.ArrayList;
import java.util.List;

public class ListNode {
    private int val;
    private ListNode next;

    public ListNode() {}

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val; this.next = next;
    }
    //低阶版
    //先将结果写入list集合,然后倒序遍历list集合,将结果写入ListNote链表
    static class Solution3 {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode l=new ListNode();
            List<Integer> list = new ArrayList<>();
            boolean flag = false;//进位标志符
            while (true){
                if (l1==null&&l2==null) {
                    if (flag)list.add(1);//最后判断是否有进位
                    break;
                }
                int n1=0,n2=0;
                if (l1!=null){
                    n1 = l1.val;
                    l1 = l1.next;
                }
                if (l2!=null){
                    n2 = l2.val;
                    l2 = l2.next;
                }
                int sum = n1+n2;
                if (flag) {//查看是否进位
                    sum = sum + 1;
                    flag = false;
                }
                list.add(sum%10);//将个位数写入list集合
                if (sum > 9){//判断是否要进位
                    flag = true;
                }
            }
            for (int i = list.size()-1;i>=0;i--){
                if (i == list.size()-1){
                    l = new ListNode(list.get(i));
                }else{
                    l = new ListNode(list.get(i),l);
                }
            }
            return l;
        }
    }
	//测试
    public static void main(String[] args) {
        ListNode l1 = new ListNode(
            9,new ListNode(4,new ListNode(7,new ListNode(9))));
        ListNode l2 = new ListNode(5,new ListNode(6,new ListNode(4)));
        ListNode ll = new Solution3().addTwoNumbers(l1,l2);
        while (ll != null){
            System.out.println(ll.val);
            ll = ll.next;
        }
    }
}

如果不想使用内部类的方式,将ListNote类的get和set方法补齐。如下:

package com.liko.t1.bean;

public class ListNode1 {
    private int val;
    private ListNode1 next;

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }

    public ListNode1 getNext() {
        return next;
    }

    public void setNext(ListNode1 next) {
        this.next = next;
    }

    public ListNode1() {}

    public ListNode1(int val) {
        this.val = val;
    }

    public ListNode1(int val, ListNode1 next) {
        this.val = val; this.next = next;
    }
}

测试类

package com.liko.t1;

import com.liko.t1.bean.ListNode1;

public class testListNode1 {
    public static void main(String[] args) {
        ListNode1 l1 = new ListNode1(
            9,new ListNode1(4,new ListNode1(7,new ListNode1(9))));
        ListNode1 l2 = new ListNode1(5,new ListNode1(6,new ListNode1(4)));
        ListNode1 ll = new SolutionListNode1().addTwoNumbers(l1,l2);
        while (ll != null){
            System.out.println(ll.getVal());
            ll = ll.getNext();
        }
    }
}
//进阶版
//使用指针的方式,直接将结果写入ListNote链表
class SolutionListNode1{
    public ListNode1 addTwoNumbers(ListNode1 l1, ListNode1 l2) {
        ListNode1 l = new ListNode1();
        ListNode1 ne = l;
        int carry = 0;//进位符
        while(l1!=null||l2!=null){
            int l1_val = (l1 == null?0:l1.getVal());
            int l2_val = (l2 == null?0:l2.getVal());
            int sum = l1_val+l2_val+carry;

            carry = sum/10;
            sum%=10;
            ne.setNext(new ListNode1(sum));
            ne = ne.getNext();//将指针指向下一位

            if (l1!=null)l1 = l1.getNext();
            if (l2!=null)l2 = l2.getNext();
        }
        if (carry == 1)ne.setNext(new ListNode1(carry));
        return l.getNext();
    }
}

### 关于 LeetCode Java 解方法及示例代码 #### 常见的 LeetCode Java 目类型概述 LeetCode 上的 Java 目涵盖了多种算法数据结构,主要包括数组、链表、字符串、哈希表、动态规划、回溯法等。这些目通常会考察基本的数据结构操作以及高级算法的应用能力[^1]。 以下是几个典型的 LeetCode Java 目及其解决方案: --- #### 示例一:两数之和 (Two Sum) 这是一个经典的入门级问,目标是从数组中找到两个相加等于特定值 `target` 的索引。 ##### 思路 通过使用 HashMap 来存储已经遍历过的数值及其对应的索引位置,可以有效地减少时间复杂度到 O(n)。 ##### 实现代码 ```java import java.util.HashMap; public class TwoSum { public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } } ``` --- #### 示例二:移除元素 (Remove Element) 此问是要求删除数组中的指定元素并返回新长度。 ##### 思路 利用双指针技术,在原地修改数组的同时保持空间复杂度为 O(1),并通过一次遍历来完成任务[^4]。 ##### 实现代码 ```java public class RemoveElement { public int removeElement(int[] nums, int val) { int k = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[k++] = nums[i]; } } return k; } } ``` --- #### 示例三:组合总和 (Combination Sum) 该问的目标是找出所有满足条件的不同整数组合,使得它们的和等于目标值。 ##### 思路 采用递归的方式解决这个问,并结合剪枝优化来提高效率。注意这里的输入保证了不同的组合数量不会超过 150 种[^3]。 ##### 实现代码 ```java import java.util.ArrayList; import java.util.List; public class CombinationSum { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> result = new ArrayList<>(); backtrack(result, new ArrayList<>(), candidates, target, 0); return result; } private void backtrack(List<List<Integer>> result, List<Integer> tempList, int[] candidates, int remain, int start) { if (remain < 0) return; else if (remain == 0) result.add(new ArrayList<>(tempList)); else { for (int i = start; i < candidates.length; i++) { tempList.add(candidates[i]); backtrack(result, tempList, candidates, remain - candidates[i], i); tempList.remove(tempList.size() - 1); } } } } ``` --- #### 示例四:队列的最大值 (Max Queue) 这是另一个涉及设计自定义数据结构的问,目的是支持快速获取最大值的操作。 ##### 怋想 可以通过维护一个辅助队列来跟踪当前窗口内的最大值,从而达到常数时间内查询的效果[^5]。 ##### 实现代码 ```java class MaxQueue { Deque<Integer> queue; Deque<Integer> maxDeque; public MaxQueue() { this.queue = new LinkedList<>(); this.maxDeque = new LinkedList<>(); } public int max_value() { if (!maxDeque.isEmpty()) { return maxDeque.peekFirst(); } else { return -1; } } public void push_back(int value) { while (!maxDeque.isEmpty() && maxDeque.peekLast() < value) { maxDeque.pollLast(); } maxDeque.offer(value); queue.offer(value); } public int pop_front() { if (queue.isEmpty()) { return -1; } int front = queue.poll(); if (front == maxDeque.peekFirst()) { maxDeque.pollFirst(); } return front; } } ``` --- #### 注意事项 在实际编写代码过程中需要注意细节处理,比如 Map 中键类型的正确选择应为 `Character` 而不是原始类型 `char`,这是因为后者无法自动装箱成对象形式用于集合类容器中[^2]。 此外,熟悉 String 类常用方法如 replace 和其他工具函数也是很有帮助的,尤其是在面对大量字符串相关目时能够更加得心应手。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值