leetCode--两数之和和两数相加

两数之和

1.题目

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the sameelement twice.

Example:

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

分析:

就是给定一个数,在列表中找到两个数的和是这个,把下标输出出来。最简单的方式就是用for循环,比如下面的代码:

1
2
3
4
5
6
7
8
9
list=[]
numsLen = len(nums)
for i in range(numsLen):
for k in range(i+1,numsLen):
if nums[i]+nums[k]==target:
list.append(i)
list.append(k)
return list
return None

这个最好理解的,就是for循环,从第一个开始循环,然后再循环剩下的数入,如果两个数加起来是目标数值,就返回。在一个从小到大有序的数组是非常快。但是如果这个数组中数值是无序就比较慢了(只能跑赢20%左右的python代码)。

下面给出一个无序比较快的一段查找代码:

1
2
3
4
5
6
7
8
a={}
for i,value in enumerate(nums):
if target-value in a:
return [a[target-value],i]
else:
a[value] = i

return None

这个代码的思路,一次循环就能做出来,用了字典,key是数组的值,value是数组的下标。然后利用字典的查询特点快速找到值,取出下标(跑赢100%)。

两个列表之和

题目

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.

Example:

1
2
3
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

分析:

就是把两个链表上的数值相加,最终得到一个链表的值。有点像竖式运算。所以就只能循环链表,把数值相加。注意,超过9的话会进1。简单的代码如下:

1
2
3
4
5
6
7
8
9
10
cur = result =ListNode(0)
a=0
while l1 or l2 or a != 0:
k = (l1.val if l1 else 0) + (l2.val if l2 else 0) + a
a = k / 10
cur.next = ListNode(k % 10)
cur = cur.next
l1 = l1.next if l1 else None
l2 = l2.next if l2 else None
return result.next

这个里面就是有很多判断条件,只能跑赢40%左右的python代码,下面又做了一些改进

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
cur = result =ListNode(0)
carry=0
a=0
while l1 and l2:
k = l1.val+l2.val+carry
carry=k//10
cur.next=ListNode(k%10)
cur = cur.next
l1 = l1.next
l2 = l2.next
while l1:
k = carry+l1.val
carry=k//10
cur.next=ListNode(k%10)
cur = cur.next
l1 = l1.next
while l2:
k = carry+l2.val
carry=k//10
cur.next=ListNode(k%10)
cur = cur.next
l2 = l2.next
if carry!=0:
cur.next=ListNode(carry)
cur = cur.next
return root.next

这个代码比上一个代码只能提升一点点,怎么能跑赢超过一半的python代码,不知道大家有没有比较好的想法,可以交流一下