题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }

        ListNode h1 = head1;
        ListNode h2 = head2;

        List<Integer> str1 = new ArrayList<>();
        List<Integer> str2 = new ArrayList<>();
        int ii = 0;
        while (h1 != null) {
            str1.add(h1.val);
            h1 = h1.next;
        }

        //System.out.println("11遍历完第一个:" + System.currentTimeMillis());
        ii = 0;
        while (h2 != null) {
            str2.add(h2.val);
            h2 = h2.next;
        }
        //System.out.println("11遍历完第二个:" + System.currentTimeMillis());
        //Stack<Integer> stack = new Stack<>();
        int p = 0;
        int index = 1;
        int[] res = new int[Math.max(str1.size(), str2.size()) + 1];
        int q = 0;
        //System.out.println("1:" + System.currentTimeMillis());
        for (int i = str1.size() - 1, j = str2.size() - 1; i >= 0 ||
                j >= 0; i--, j--, index *= 10, q++) {

            if (i < 0) {
                int i1 = (str2.get(j) + p);
                //stack.add(i1 % 10);
                res[q] = (i1 % 10);
                p = i1 / 10;
                continue;
            }
            if (j < 0) {
                int i1 = (str1.get(i) + p);
                //stack.add(i1 % 10);
                res[q] = (i1 % 10);
                p = i1 / 10;
                continue;
            }
            int i1 = (str2.get(j)) + (str1.get(i)) + p;
            //stack.add(i1 % 10);
            res[q] = (i1 % 10);
            p = i1 / 10;
        }
        if (p != 0) {
            //stack.add(p);
            res[q] = p;
        }
        //System.out.println("2:" + System.currentTimeMillis());
        ListNode cur = new ListNode(-999);
        ListNode head = cur;
        for (int i = res.length - 1; i >= 0; i--) {
            cur.next = new ListNode(res[i]);
            cur = cur.next;
        }
        //System.out.println("3:" + System.currentTimeMillis());
        return head.next.val == 0 ? head.next.next : head.next;
    }
}

耗时点:

  1. 不能用字符串
  2. 如果用fori遍历不要用LinkedList
全部评论

相关推荐

06-25 21:00
门头沟学院 Java
多拆解背记一下当前的高频场景面试题,结合自己的项目经历去作答,面试通过率原来真的不会低!
牛客96559368...:小公司不就是这样的吗,面试要么是点击就送,要么就是往死里拷打,没有一个统一的标准。这个不能代表所有公司
点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
点赞 评论 收藏
分享
“校招”、“3-5年经验”
xiaolihuam...:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务