- Merge Two Sorted Lists
**思路:二路归并,用链表的数据结构
将链表的表头虚化,然后比较两个排序列表的数值,小的先接到新的链表的Next节点,旧链表往后移。有了新值后,新链表往后移。最后直接连接剩余链表。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if l1 == None and l2 == None:
return None
if l1 == None:
return l2
if l2 == None:
return l1
ret = ListNode(0)
head = ret
while l1 != None and l2 != None:
if l1.val <=l2.val:
ret.next = l1
l1 = l1.next
else:
ret.next = l2
l2 = l2.next
ret = ret.next
if l1 == None:
ret.next = l2
if l2 == None:
ret.next = l1
return head.next
- Remove Duplicates from Sorted Array
**思路:新数组不能开辟新的空间,那就在原数组基础上,如果两两不等,he原数组一样,如果出现不同,数组就跳过。nums[j]相当于新数组最后一个元素,所以返回的是j+1
class Solution(object):
def removeDuplicates(self, nums):
if len(nums)==0:
return 0
j=0
for i in range(1,len(nums)):
if nums[i]!=nums[j]:
nums[j+1]=nums[i]
j=j+1
return j+1
网友评论