zoukankan      html  css  js  c++  java
  • leetcode 445. Add Two Numbers II

    题目内容

    You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

    You may assume the two numbers do not contain any leading zero, except the number 0 itself.

    Follow up:
    What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

    Example:
    Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
    Output: 7 -> 8 -> 0 -> 7
    

    分析过程

    • 题目归类:
      递归,链表
    • 题目分析:
      需要把两个链加起来,需要从后向前加。
      两种方法
      1. 直接逆转链然后按照two sum的方式求解。
        2.根据递归可以现到最末端让后开始相加,返回一个ListNode知道完全返回。
        我采用第二种方法,让两个链末端对齐。
    • 边界分析:
      • 空值分析
        开始计算的时候一定是两个链指向null的前一个。
      • 循环边界分析
    • 方法分析:
      • 数据结构分析
        递归,写在递归函数前面的会先做,写在递归后面的会最后做。因为本题需要计算最后的数据,所以先递归再计算。
      • 状态机
      • 状态转移方程
      • 最优解
    • 测试用例构建
      [0],[0];

    代码实现

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        int carry = 0;
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            int l1Length = 0;
            int l2Length = 0;
            ListNode l1Tmp = l1;
            ListNode l2Tmp = l2;
            while(l1!=null){
                l1Length++;
                l1 = l1.next;
            }
            while(l2!=null){
                l2Length++;
                l2 = l2.next;
            }
            ListNode tmp;
            if(l1Length>=l2Length){
                tmp=  addPlus(l1Tmp,l2Tmp,l1Length-l2Length);
            }else{
                tmp=  addPlus(l2Tmp,l1Tmp,l2Length-l1Length);
            }
            if(carry!=0){
                ListNode head = new ListNode(carry);
                head.next = tmp;
                tmp = head;
            }
            return tmp;
        }
        public ListNode addPlus(ListNode l1,ListNode l2,int length) {
            if(l1==null&&l2==null)
                return null;
            ListNode tmp;
            if(length!=0){
                 tmp = addPlus(l1.next,l2,length-1);
            }else{
                 tmp = addPlus(l1.next, l2.next,0);
            }
            int sum = (l1==null?0:l1.val)+(l2==null||length!=0?0:l2.val)+carry;
            ListNode head = new ListNode(sum%10);
            head.next = tmp;
            carry = sum /10;
            return head;
        }
    }
    

    效率提高


    效率还可以,但是代码有一点臃肿。

  • 相关阅读:
    全排列 next_permutation()函数
    hdu1247
    hdu3518
    pku2774 求最长公共子串
    hdu3460 Ancient Printer
    pku2001
    pku 3261
    NOI.AC#2007light【根号分治】
    CF1370F2The Hidden Pair(Hard Version)【交互题,二分】
    P3335[ZJOI2013]蚂蚁寻路【dp】
  • 原文地址:https://www.cnblogs.com/clnsx/p/12252157.html
Copyright © 2011-2022 走看看