leetCode之Add Two Numbers python实现
来源:互联网 发布:手机淘宝里的跳蚤街 编辑:程序博客网 时间:2024/06/10 19:07
2 Add Two Numbers
- 要求:
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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. - 题目大意:给定两个非空链表,链表中每个节点表示一个数,所有节点表示一个整数,且是反向存储的,也就是说假如列表是1->2->3,表示321。给这两个链表求和并返回。你可以假设这两个链表都不会以0作为最高位,除非是就是一个0。
2.1 补零相加(自取)
- 解题思路:首先用两个列表保存传入链表的所有值,并进行高位补零操作(使两个数位数相等)。然后就是对应每一位相加,逢十进一。
- 时间复杂度O(n)
- 运行时间:222ms
class Solution: def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ l1_tmp = [] l2_tmp = [] while l1 != None: l1_tmp.append(l1.val) l1 = l1.next while l2 != None: l2_tmp.append(l2.val) l2 = l2.next # print(l1_tmp) # print(l2_tmp) if len(l1_tmp) > len(l2_tmp): for i in range(len(l1_tmp) - len(l2_tmp)): l2_tmp.append(0) if len(l1_tmp) < len(l2_tmp): for i in range(len(l2_tmp) - len(l1_tmp)): l1_tmp.append(0) # 初始化 two_sum = [] for i in range(len(l2_tmp)): two_sum.append(0) flag = 0 for i in range(len(l2_tmp)): two_sum[i] = l2_tmp[i] + l1_tmp[i] + flag flag = 0 if two_sum[i] >= 10: two_sum[i] = two_sum[i] - 10 flag = 1 if flag == 1: two_sum.append(1) return two_sum
2.2 改进版
- 解题思路:第一个版本写的太烂了,又是就有了这个改进版。直接从两个链表的第一个数相加,如果相加之和大于等于10,则进一。如果其中一个链表为None,另外一个链表不为None,那么为None的那个链表最高位补零。
- 时间复杂度:O(n)
- 运行结果:198ms
class ListNode: def __init__(self, x): self.val = x self.next = Noneclass Solution: def addTwoNumbers(self, l1, l2): two_sum = [] flag = 0 while l1 != None or l2 != None: if l1 == None: l1 = ListNode(0) if l2 == None: l2 = ListNode(0) sum_tmp = l1.val + l2.val + flag flag = 0 if sum_tmp >= 10: sum_tmp = sum_tmp - 10 flag = 1 two_sum.append(sum_tmp) l1 = l1.next l2 = l2.next if flag == 1: two_sum.append(1) return two_sum
阅读全文
0 0
- leetCode之Add Two Numbers python实现
- [leetcode]-add two numbers @python
- 【Leetcode】【python】Add Two Numbers
- leetcode之Add Two Numbers
- LeetCode 之 Add Two Numbers
- leetcode之Add Two Numbers
- LeetCode之Add Two Numbers
- leetcode之Add Two Numbers
- leetcode之Add Two Numbers
- 【LeetCode】之Add Two Numbers
- LeetCode之Add Two Numbers
- leetcode之Add Two Numbers
- leetCode之 Add Two Numbers
- LeetCode之Add Two Numbers
- [LeetCode]4 Add Two Numbers(C++,Python实现)
- LeetCode 2. Add Two Numbers (C++/python/js实现)
- [Leetcode] Add Two Numbers Python实现 详细讲解
- 【LeetCode】【Python】【C++】2. Add Two Numbers代码实现
- 你应该要懂的宇宙真相——《给忙碌者的天体物理学 》上篇
- UILabel笔记
- 你不知道的Chrome开发者工具新功能
- 第14节:scala编程之集合
- 指针定义与运算
- leetCode之Add Two Numbers python实现
- Maximum Subarray Difference
- 导入表注入
- pytorch学习笔记(十四): DataLoader源码阅读
- VI编辑器基本使用方法
- 火车票购买系统模拟
- C#基础(16)——ArrayList
- 【机房收费系统】登录显示多步OLE DB 错误
- 小白学PyQt5(1):环境搭建