**
python刷题
**
python刷题
- python刷题
- 前言
- 一、目的
- 二、题目
- 1.用两个栈实现队列
- 2.包含min函数的栈
- 3.从尾到头打印链表
- 4.反转链表
- 5.复杂链表的复制
- 6.替换空格
- 7.左旋转字符串
- 7.数组中重复的数字
- 8.在排序数组中查找数字
- 9.从上到下打印二叉树 II
- 10.从上到下打印二叉树 III
- 11.树的子结构
- 12. 对称的二叉树
- 13.斐波那契数列
- 14.连续子数组的最大和
- 15.把数字翻译成字符串
- 16.最长不含重复字符的子字符串
- 17.链表中倒数第k个节点
- 18.合并两个排序的链表
- 19.两个链表的第一个公共节点
- 总结
前言
LeetCode刷题记录。
一、目的
二、题目
1.用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
代码如下(示例):
class CQueue:
def __init__(self):
self.A, self.B = [], []
def appendTail(self, value: int) -> None:
self.A.append(value)
def deleteHead(self) -> int:
if self.B: return self.B.pop()
if not self.A: return -1
while self.A:
self.B.append(self.A.pop())
return self.B.pop()
2.包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的 min 函数在该栈中,调用 min、push 及 pop 的时间复杂度都是 O(1)。
代码如下(示例):
class MinStack:
def __init__(self):
self.A, self.B = [], []
def push(self, x: int) -> None:
self.A.append(x)
if not self.B or self.B[-1] >= x:
self.B.append(x)
def pop(self) -> None:
if self.A.pop() == self.B[-1]:
self.B.pop()
def top(self) -> int:
return self.A[-1]
def min(self) -> int:
return self.B[-1]
3.从尾到头打印链表
输入一个链表的头结点,从尾到头反过来返回每个节点的值(用数组返回)。
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
res = []
while head:
res.append(head.val)
head = head.next
return res[::-1] # 或者 reverse(res)
4.反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
cur, pre = head, None
while cur:
tmp = cur.next # 暂存后继节点 cur.next
cur.next = pre # 修改 next 引用指向
pre = cur # pre 暂存 cur
cur = tmp # cur 访问下一节点
return pre
5.复杂链表的复制
请实现 copyRandomList 函数,复制一个复杂链表。在复杂链表中,每个节点除了有一个 next 指针指向下一个节点,还有一个 random 指针指向链表中的任意节点或者 null。
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if not head: return
dic = {}
# 3. 复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
cur = head
while cur:
dic[cur] = Node(cur.val)
cur = cur.next
cur = head
# 4. 构建新节点的 next 和 random 指向
while cur:
dic[cur].next = dic.get(cur.next)
dic[cur].random = dic.get(cur.random)
cur = cur.next
# 5. 返回新链表的头节点
return dic[head]
6.替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
class Solution:
def replaceSpace(self, s: str) -> str:
res = []
for c in s:
if c == ' ': res.append("%20")
else: res.append(c)
return "".join(res)
7.左旋转字符串
字符串的左旋转操作是把字符串前面的若干个字符转移到字符串的尾部。请定义一个函数实现字符串左旋转操作的功能。比如,输入字符串"abcdefg"和数字2,该函数将返回左旋转两位得到的结果"cdefgab"。
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
return s[n:] + s[:n]
7.数组中重复的数字
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
class Solution:
def findRepeatNumber(self, nums: [int]) -> int:
dic = set()
for num in nums:
if num in dic: return num
dic.add(num)
return -1
8.在排序数组中查找数字
统计一个数字在排序数组中出现的次数。
class Solution:
def search(self, nums: [int], target: int) -> int:
# 搜索右边界 right
i, j = 0, len(nums) - 1
while i <= j:
m = (i + j) // 2
if nums[m] <= target: i = m + 1
else: j = m - 1
right = i
# 若数组中无 target ,则提前返回
if j >= 0 and nums[j] != target: return 0
# 搜索左边界 left
i = 0
while i <= j:
m = (i + j) // 2
if nums[m] < target: i = m + 1
else: j = m - 1
left = j
return right - left - 1
class Solution:
def search(self, nums: [int], target: int) -> int:
def helper(tar):
i, j = 0, len(nums) - 1
while i <= j:
m = (i + j) // 2
if nums[m] <= tar: i = m + 1
else: j = m - 1
return i
return helper(target) - helper(target - 1)
9.从上到下打印二叉树 II
从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
if not root: return []
res, queue = [], collections.deque()
queue.append(root)
while queue:
tmp = []
for _ in range(len(queue)):
node = queue.popleft()
tmp.append(node.val)
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
res.append(tmp)
return res
10.从上到下打印二叉树 III
请实现一个函数按照之字形顺序打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if not root :
return res
queue = collections.deque()
queue.append(root)
i = 0
while queue :
temp = collections.deque()
for _ in range(len(queue)):
node = queue.popleft()
if i == 1 :
temp.appendleft(node.val) # 偶数层 -> 队列头部
else :
temp.append(node.val) # 奇数层 -> 队列尾部
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
i = (i+1)%2
res.append(list(temp))
return res
11.树的子结构
输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
if not A or not B:return False
queue = collections.deque()
queue.append(A)
while queue :
temp = queue.pop()
if temp.val == B.val :
queueA = collections.deque()
queueB = collections.deque()
queueA.append(temp)
queueB.append(B)
while queueA and queueB:
tempA = queueA.pop()
tempB = queueB.pop()
if tempB.left :
queueB.append(tempB.left)
if tempA.left :
if tempA.left.val != tempB.left.val : break
queueA.append(tempA.left)
else :
break
if tempB.right :
queueB.append(tempB.right)
if tempA.right :
if tempA.right.val != tempB.right.val : break
queueA.append(tempA.right)
else :
break
if not queueB :
return True
if temp.left : queue.append(temp.left)
if temp.right : queue.append(temp.right)
return False
12. 对称的二叉树
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root : return True
queue = collections.deque()
queue.append(root.left)
queueM = collections.deque()
queueM.append(root.right)
while queue or queueM:
temp = queue.pop()
tempM= queueM.pop()
if temp==None and tempM== None :
continue
elif temp==None or tempM== None :
return False
elif temp.val == tempM.val :
queue.append(temp.left)
queue.append(temp.right)
queueM.append(tempM.right)
queueM.append(tempM.left)
else : return False
return True
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def recur(L, R):
if not L and not R: return True
if not L or not R or L.val != R.val: return False
return recur(L.left, R.right) and recur(L.right, R.left)
return recur(root.left, root.right) if root else True
13.斐波那契数列
写一个函数,输入 n ,求斐波那契(Fibonacci)数列的第 n 项(即 F(N))。斐波那契数列的定义如下:
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), 其中 N > 1.
斐波那契数列由 0 和 1 开始,之后的斐波那契数就是由之前的两数相加而得出。
答案需要取模 1e9+7(1000000007),如计算初始结果为:1000000008,请返回 1。
class Solution:
def fib(self, n: int) -> int:
if n == 0 or n == 1 :return n
a , b = 0 , 1
for i in range(2,n+1) :
a , b = b , a+b
return b % 1000000007
14.连续子数组的最大和
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
for i in range(1, len(nums)):
nums[i] += max(nums[i - 1], 0)
return max(nums)
15.把数字翻译成字符串
输入一个整型数组,数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。
要求时间复杂度为O(n)。
class Solution:
def translateNum(self, num: int) -> int:
a = b = 1
y = num % 10
while num != 0:
num //= 10
x = num % 10
a, b = (a + b if 10 <= 10 * x + y <= 25 else a), a
y = x
return a
16.最长不含重复字符的子字符串
请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dic = {}
res = tmp = 0
for j in range(len(s)):
i = dic.get(s[j], -1) # 获取索引 i
dic[s[j]] = j # 更新哈希表
tmp = tmp + 1 if tmp < j - i else j - i # dp[j - 1] -> dp[j]
res = max(res, tmp) # max(dp[j - 1], dp[j])
return res
17.链表中倒数第k个节点
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
former, latter = head, head
for _ in range(k):
former = former.next
while former:
former, latter = former.next, latter.next
return latter
18.合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 : return l2
if not l2 : return l1
l3 =ListNode(None)
cur = l3
while l1 and l2 :
if l1.val >= l2.val :
cur.next = l2
cur = cur.next
l2 = l2.next
else :
cur.next = l1
cur = cur.next
l1 = l1.next
if not l1 : cur.next = l2
elif not l2 : cur.next = l1
return l3.next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
cur = dum = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next, l1 = l1, l1.next
else:
cur.next, l2 = l2, l2.next
cur = cur.next
cur.next = l1 if l1 else l2
return dum.next
19.两个链表的第一个公共节点
输入两个链表,找出它们的第一个公共节点。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
if not headA or not headB : return None
l1 = []
cur1 = headA
cur2 = headB
num = 0
print (headA.val)
print (headB.val)
while cur2 :
l1.append(cur2.val)
cur2=cur2.next
while cur1 :
if cur1.val in l1 :
return cur1
cur1=cur1.next
return None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
A, B = headA, headB
while A != B:
A = A.next if A else headB
B = B.next if B else headA
return A
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。