给定两个非空链表来代表两个非负数,位数按照逆序方式存储,它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

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

示例:

1
2
3
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807

思路非常清晰,首先两个链表长度得一致,同时逆序操作,其次返回链表时也为逆序,首先输出的📖链表头两个元素之和。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""

head = ListNode((l1.val + l2.val) % 10)
current = head
carry = (l1.val + l2.val) // 10
while l1.next is not None or l2.next is not None:
num1 = 0
num2 = 0
if l1.next is not None:
l1 = l1.next
num1 = l1.val
if l2.next is not None:
l2 = l2.next
num2 = l2.val
current.next = ListNode((num1 + num2 + carry) % 10)
carry = (num1 + num2 + carry) // 10
current = current.next
if carry != 0:
current.next = ListNode(carry)
return head

给定一个整数数列,找出其中和为特定值的那两个数。

你可以假设每个输入都只会有一种答案,同样的元素不能被重用。

示例:

1
2
3
4
5

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

使用dict

1
2
3
4
5
6
7
8
9
10

class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
dict = {}
for i in xrange(len(num)):
x = num[i]
if target-x in dict:
return (dict[target-x]+1, i+1)
dict[x] = i