3.2
题目
17. 从尾到头打印链表
class Solution(object):
def printListReversingly(self, head):
"""
:type head: ListNode
:rtype: List[int]
"""
ans=[]
headnode=head
while headnode:
ans.append(headnode.val)
headnode=headnode.next
ans.reverse()
return ans
26. 二进制中1的个数
class Solution(object):
def NumberOf1(self, n):
count = 0
# Check each bit in the binary representation of n
for i in range(32): # Assuming integers are 32 bits in your system
if n & 1: # Check if the least significant bit is 1
count += 1
n >>= 1 # Right shift n by 1 bit
return count
20. 用两个栈实现队列
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.s1=[]
self.s2=[]
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.s1.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
while len(self.s1)!=0:
self.s2.append(self.s1.pop())
p=self.s2.pop()
while len(self.s2)!=0:
self.s1.append(self.s2.pop())
return p
def peek(self):
"""
Get the front element.
:rtype: int
"""
while len(self.s1)!=0:
self.s2.append(self.s1.pop())
p=self.s2.pop()
self.s2.append(p)
while len(self.s2)!=0:
self.s1.append(self.s2.pop())
return p
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if len(self.s1)==0:
return True
else:
return False
862. 三元组排序
class trp:
def __init__(self,x,y,z):
self.x=x
self.y=y
self.z=z
n=int(input())
t=[]
for i in range(n):
x,y,z=input().split()
t.append(trp(int(x),float(y),z))
t.sort(key=lambda t:t.x)
for i in t:
print(f'{i.x} {i.y:.2f} {i.z}')
21. 斐波那契数列
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
a,b=0,1
for i in range(n):
a,b=b,a+b
return a
36. 合并两个排序的链表
class Solution(object):
def merge(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head=ListNode(-1)
node=head
while l1 and l2:
if l1.val<=l2.val:
node.next=l1
l1=l1.next
else:
node.next=l2
l2=l2.next
node=node.next
if l1:
node.next=l1
else:
node.next=l2
return head.next
78. 左旋转字符串
class Solution(object):
def leftRotateString(self, s, n):
"""
:type s: str
:type n: int
:rtype: str
"""
ss=s*2
return ss[n:len(s)+n]
87. 把字符串转换成整数
class Solution(object):
def strToInt(self, s):
"""
:type str: str
:rtype: int
"""
s = s.strip()
import re, sys
ans = re.match(r'[+-]?\d+', s)
if ans:
n = int(ans.group())
if n > 2**31-1:
return 2**31-1
elif n < -2**31:
return -2**31
return n
else:
return 0
35. 反转链表
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
# 反转后的头结点,原链表的尾结点
new_head = self.reverseList(head.next)
# 将当前节点的下一个节点的 next 指针指向当前节点
head.next.next = head
# 将当前节点的 next 指针置空
head.next = None
return new_head
class Solution:
def reverseList(self, head):
prev = None
cur = head
while cur:
next = cur.next
cur.next = prev
prev = cur
cur = next
return prev
66. 两个链表的第一个公共结点
class Solution(object):
def findFirstCommonNode(self, headA, headB):
"""
:type headA, headB: ListNode
:rtype: ListNode
"""
a=headA
b=headB
while a!=b:
a=a.next if a else headB
b=b.next if b else headA
return a
29. 删除链表中重复的节点
class Solution(object):
def deleteDuplication(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy=ListNode(0)
dummy.next=head
pre=dummy
while pre.next:
cur=pre.next
while cur and cur.val==pre.next.val:
cur=cur.next
if pre.next.next==cur:
pre=pre.next
else:
pre.next=cur
return head
821. 跳台阶
def fun(n):
if n==1:
return 1
if n==2:
return 2
return fun(n-1)+fun(n-2)
print(fun(int(input())))
822. 走方格
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
n,m=map(int,input().split())
print(int(factorial(m+n)/(factorial(m)*factorial(n))))
count = 0
def dfs(x, y):
global count # 声明count为全局变量
if (x == n and y == m):
count += 1
if x < n:
dfs(x + 1, y)
if y < m:
dfs(x, y + 1)
n, m = map(int, input().split())
dfs(0, 0) # 修改起始点为(0, 0)
print(count)
823. 排列
def dfs(cur, start):
global path,st,arr,ans
if cur == len(arr):
ans.append(path[:])
return
for i in range(start, len(arr)):
if not st[i]:
st[i] = True
path[cur] = arr[i]
dfs(cur + 1, 0) # 从索引0开始搜索下一个数字
st[i] = False
n = int(input())
arr = [x for x in range(1, n + 1)]
ans = []
path = [0] * n
st = [False] * n
dfs(0, 0)
for i in ans:
for j in i:
print(j,end=' ')
print()
822. 走方格
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
n,m=map(int,input().split())
print(int(factorial(m+n)/(factorial(m)*factorial(n))))
count = 0
def dfs(x, y):
global count # 声明count为全局变量
if (x == n and y == m):
count += 1
if x < n:
dfs(x + 1, y)
if y < m:
dfs(x, y + 1)
n, m = map(int, input().split())
dfs(0, 0) # 修改起始点为(0, 0)
print(count)
772. 只出现一次的字符
if __name__ == '__main__':
s = input()
sign=0
for i in s:
if s.find(i)==s.rfind(i):
print(i)
sign=1
break
if sign==0:
print('no')
if __name__ == '__main__':
s = input()
d=dict()
sign=0
for i in s:
d[i]=0
for i in s:
d[i]+=1
for k,v in d.items():
if v==1:
print(k)
sign=1
break
if sign==0:
print('no')
Tips
lambda表达式
当使用lambda函数时,它可以自动获取其所在作用域中的变量,并将其作为参数传递给lambda函数。Lambda函数是一种匿名函数,它可以在需要函数对象的地方使用,并且通常用于简单的函数功能。
lambda函数的语法如下:
lambda arguments: expression
lambda函数的参数部分可以包含多个参数,用逗号分隔。在lambda函数体中,可以使用这些参数并返回一个表达式的值。lambda函数通常用于需要一个简单的函数对象而不想定义一个完整的函数的场景。
在lambda函数中,参数是自动传入的,不需要显式地进行传参。当我们调用lambda函数时,它会自动获取其所在作用域中的变量,并将其作为参数传递给lambda函数。
例如,考虑以下示例代码:
x = 10
y = 20
result = (lambda a, b: a + b)(x, y)
print(result)
在这个例子中,我们定义了两个变量 x 和 y,然后我们使用lambda函数来计算它们的和。lambda函数 (lambda a, b: a + b) 接受两个参数 a 和 b,并返回它们的和。我们通过在lambda函数后面的括号中传递参数 x 和 y 来调用lambda函数,并将计算结果赋值给变量 result。最后,我们打印出 result 的值。
在lambda函数被调用时,它自动获取了 x 和 y 这两个变量,并将它们作为参数 a 和 b 传递给lambda函数。lambda函数执行表达式 a + b,计算出 x + y 的结果,并返回该结果。因此,最终的输出为 30。
dummy哑结点
哑节点(dummy node)是一个在链表开头额外添加的虚拟节点,它的作用是简化链表的操作,特别是在处理边界情况时非常有用。以下是哑节点的几个好处:
- 处理边界情况:在链表操作中,处理头节点和尾节点通常需要特殊处理。使用哑节点可以将这些边界情况与一般情况统一起来,简化了代码逻辑。
- 简化插入和删除操作:在某些链表操作中,需要在头部或尾部插入或删除节点。使用哑节点可以避免对头节点或尾节点进行特殊处理,只需对普通节点进行操作,简化了代码的编写和理解。
- 简化链表遍历:在某些情况下,需要对链表进行遍历并对每个节点进行操作。使用哑节点可以使遍历过程更加统一,无需单独处理头节点的情况。
- 提高代码可读性:哑节点的存在可以使链表操作的代码逻辑更加清晰和易读,减少了对特殊情况的处理,使代码更加简洁。
总之,哑节点是一种常用的技巧,可以简化链表操作的代码逻辑,提高可读性,并统一了对边界情况的处理。它在处理链表时经常被使用,特别是在涉及头节点和尾节点的操作中,使用哑节点可以使代码更加简洁和易于理解。
排列 组合 公式
组合数和排列数是组合数学中的两个重要概念。下面分别介绍组合数和排列数的计算方法。
- 组合数(Combination):
组合数表示从n个元素中选择k个元素的不同组合的数量,不考虑元素的顺序。组合数通常用C(n, k)或者(n choose k)表示。组合数的计算可以使用以下公式:
C(n, k) = n! / (k! * (n-k)!)
其中,n!表示n的阶乘,即n! = n (n-1) (n-2) … 2 * 1。 - 排列数(Permutation):
排列数表示从n个元素中选择k个元素的不同排列的数量,考虑元素的顺序。排列数通常用P(n, k)表示。排列数的计算可以使用以下公式:
P(n, k) = n! / (n-k)!
其中,n!表示n的阶乘,即n! = n (n-1) (n-2) … 2 * 1。
在实际编程中,可以使用循环或递归的方式计算组合数和排列数。下面是使用Python语言的示例代码:
计算组合数
def combination(n, k):
if k > n:
return 0
elif k == 0 or k == n:
return 1
else:
numerator = 1
denominator = 1
for i in range(k):
numerator *= n-i
denominator *= i+1
return numerator // denominator
#计算排列数
def permutation(n, k):
if k > n:
return 0
else:
result = 1
for i in range(k):
result *= n-i
return result
示例用法
n = 5
k = 3
print(“组合数 C({}, {}) = {}”.format(n, k, combination(n, k)))
print(“排列数 P({}, {}) = {}”.format(n, k, permutation(n, k)))
上述代码中,combination函数计算组合数,permutation函数计算排列数。通过传入不同的n和k值,可以计算不同的组合数和排列数。
全局变量
函数中使用全局变量要先声明
global关键字
3.1
算法题
68. 0到n-1中缺失的数字
class Solution(object):
def getMissingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
for i in range(len(nums)+1):
if i not in nums:
return i
class Solution(object):
def getMissingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return 0
l,r=0,len(nums)-1
while l<r:
mid=l+r>>1
if (nums[mid]!=mid):
r=mid
else:
l=mid+1
if nums[l]==l:
l+=1
return l
75. 和为S的两个数字
class Solution(object):
def findNumbersWithSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
ans=[]
for i in nums:
if target-i in nums:
if target-i==i and nums.count(i)==1:
continue
ans.append(i)
ans.append(target-i)
return ans
32. 调整数组顺序使奇数位于偶数前面
class Solution(object):
def reOrderArray(self, array):
"""
:type array: List[int]
:rtype: void
"""
odd=[]
even=[]
for i in array:
if i%2!=0:
odd.append(i)
else:
even.append(i)
ans=odd+even
for i in range(len(ans)):
array[i]=ans[i]
class Solution(object):
def reOrderArray(self, array):
"""
:type array: List[int]
:rtype: void
"""
l,r=0,len(array)-1
while l<r:
while l<r and array[l]%2!=0:
l+=1
while l<r and array[r]%2==0:
r-=1
array[l],array[r]=array[r],array[l]
51. 数字排列
class Solution:
def permutation(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
import itertools as it
i=list(it.permutations(nums))
ans=set([x for x in i])
return list(ans)
Tips
isnumeric(), isdigit(), 和 isdecimal()
在Python中,字符串对象有三个方法用于检测字符串是否包含数字:isnumeric(), isdigit(), 和 isdecimal()。它们各自的功能和适用场景略有不同:
- isdigit()
○ 此方法用于检测字符串中的字符是否全部属于十进制数字(0-9)。
○ 它仅识别ASCII数字,即英文数字字符(“0”-“9”)。
○ 如果字符串中所有字符都是十进制数字,则返回True,否则返回False。 - isnumeric()
○ 这个方法更广泛,它检测字符串中的字符是否代表数值,不仅包括十进制数字,还包括其他类型的数字字符,如汉字数字或其他Unicode编码中的数字字符。
○ 对于Unicode编码,它会识别出像是罗马数字、阿拉伯数字以及其他文化中表示数字的字符。
○ 如果字符串中所有字符都代表数值,则返回True,否则返回False。 - isdecimal()
○ 此方法类似于isdigit(),但它是Unicode-aware的,专门用于检测字符串中的字符是否都是Unicode decimal数字(十进制数字)。
○ 它只会识别Unicode中的十进制数字字符,而不包括其他类型的数字字符,如罗马数字或其他非十进制的Unicode数字。
○ 如果字符串中所有字符都是Unicode十进制数字,则返回True,否则返回False。
总结起来,isdigit()是最窄的检测范围,仅适用于ASCII数字;isdecimal()与isdigit()相似,但在Unicode环境下只针对十进制数字;而isnumeric()的检测范围最广,涵盖了Unicode中的所有数字字符。在处理通用文本尤其是多语言文本时,选择合适的函数非常重要。
列表排序
list.sort( key=None, reverse=False)
key为函数方法
Lambda
表达式是一种简洁的匿名函数,它允许你在一行代码中定义一个函数。Lambda 表达式在 Python 中主要用于简洁地定义回调函数(Callback Function)或在需要函数对象的地方作为参数传递。
下面是一个简单的示例,展示了如何使用 lambda 表达式:
定义一个列表
numbers = [1, 2, 3, 4, 5]
使用 lambda 表达式对列表进行排序
sorted_numbers = sorted(numbers, key=lambda x: x * x)
#打印排序后的结果
print(sorted_numbers)
在上面的示例中,我们使用 lambda 表达式定义了一个匿名函数,该函数接受一个参数 x,并返回 x 的平方。然后,我们将这个 lambda 函数作为 key 参数传递给 sorted 函数,以便按照元素的平方进行排序。最后,我们打印出排序后的结果。
Lambda 表达式的一般形式如下:
lambda arguments: expression
其中,arguments 是可选的参数列表,expression 是表达式,该表达式的结果将作为 lambda 函数的返回值。
需要注意的是,lambda 表达式是一种匿名函数,因此它没有名称。它通常在需要一个简单函数的地方使用,而不需要为该函数定义一个单独的函数。
二分模板
def bsearch_1eft(l, r)
{
while (l < r):
mid=l+r>>1
if (check(mid)) mid=r
l=mid+1
}
def bsearch_right( l, r)
{
while l<r:
mid=l+r+1>>1
if (check(mid)) l=mid
else: r=mid-1
}