展示内容:一次遍历 将结果输出、而不是判断大小、再做其他冗余处理
88 合并两个有序数组
版本一
class Solution:
def merge(self , A, m, B, n):
if n ==0: return A
if m ==0:
A[:] = B[:]
return A
total, m, n = m+n-1, m-1, n-1
while m>=0 or n>=0:
cur_A = A[m] if m>=0 else -10000
cur_B = B[n] if n>=0 else -10000
if cur_A >= cur_B:
A[total] = cur_A
m -= 1
else:
A[total] = cur_B
n -= 1
total -= 1
return A
版本二
class Solution(object):
def merge(self, nums1, m, nums2, n):
if m<=0:
nums1[:] = nums2[:]
return nums1
if n<=0: return nums1
i ,j, length = m-1, n-1, m+n-1
while i>=0 or j>=0 :
if i>=0 and (j <0 or nums1[i]>= nums2[j]):
nums1[length] = nums1[i]
i -= 1
else:
nums1[length] = nums2[j]
j -= 1
length -=1
return nums1
class Solution:
def addInList(self , head1 , head2 ):
# write code here
def reverseList(head):
cur, p = None, head
while p:
tmp = p.next
p.next = cur
cur = p
p = tmp
return cur
p1 = reverseList(head1)
p2 = reverseList(head2)
carry = 0
cur_head = None
while p1 or p2:
val1 = p1.val if p1 else 0
val2 = p2.val if p2 else 0
v = (val1 + val2 + carry) % 10
carry = (val1 + val2 + carry) / 10
node = ListNode(v)
node.next = cur_head
cur_head = node
if p1: p1=p1.next
if p2: p2=p2.next
if carry:
node = ListNode(carry)
node.next = cur_head
cur_head = node
return cur_head