0
点赞
收藏
分享

微信扫一扫

LeedCode刷题(21、24、26、27、28)


目录

​​一、合并两个有序链表​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

​​二、两两交换链表中的结点​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

​​三、删除有序数组中的重复项​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

​​四、移除元素​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

​​五、 实现strStr()​​

​​1、题目描述​​

​​2、题解​​

​​3、源码​​

一、合并两个有序链表

1、题目描述

LeedCode刷题(21、24、26、27、28)_有序数组

 

2、题解

LeedCode刷题(21、24、26、27、28)_有序数组_02

3、源码

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
prehead = ListNode(-1)
prev = prehead
while list1 and list2:
if list1.val <= list2.val:
prev.next = list1
list1 = list1.next
else:
prev.next = list2
list2 = list2.next
prev = prev.next

# 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
prev.next = list1 if list1 is not None else list2

return prehead.next

二、两两交换链表中的结点

1、题目描述

LeedCode刷题(21、24、26、27、28)_python_03

2、题解

LeedCode刷题(21、24、26、27、28)_初始化_04

3、源码

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:

# 空链表或者只有一个节点,直接返回
if not head or head.next == None:
return head
# 创建虚拟节点
dummyHead = ListNode(-1)
# 初始化pre、p 节点
pre = dummyHead
p = head

# 必须是节点数是偶数个的时候才能交换
# 如果最后只剩下一个节点,即链表是奇数个节点,最后一个不用反转
# 比如 head = [1,2, 3, 4, 5],输出 [2, 1, 4, 3, 5]
while p and p.next:
# 初始化 q 节点
q = p.next

# 交换节点 3 步走
pre.next = q
p.next = q.next
q.next = p

# 指针右移
pre = p
p = p.next

# 返回链表
return dummyHead.next

三、删除有序数组中的重复项

1、题目描述

LeedCode刷题(21、24、26、27、28)_链表_05

2、题解

LeedCode刷题(21、24、26、27、28)_初始化_06

 

 

LeedCode刷题(21、24、26、27、28)_链表_07

3、源码

class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
slow, fast = 0, 1
while fast < len(nums):
if nums[fast] != nums[slow]:
slow = slow + 1
nums[slow] = nums[fast]
fast = fast + 1
return slow + 1


四、移除元素

1、题目描述

LeedCode刷题(21、24、26、27、28)_初始化_08

2、题解

3、源码

class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
a = 0
b = 0

while a < len(nums):
if nums[a] != val:
nums[b] = nums[a]
b += 1
a += 1

return b

五、 实现strStr()

1、题目描述

LeedCode刷题(21、24、26、27、28)_初始化_09

 

2、题解

LeedCode刷题(21、24、26、27、28)_python_10

 

3、源码

class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if not haystack or not needle:
return 0
else:
if needle in haystack:
return haystack.index(needle)
else:
return -1

举报

相关推荐

0 条评论