给定两个数组,编写一个函数来计算它们的交集。
class Solution(object):
def intersection(self, num1, num2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
n=len(num1)
m=len(num2)
c=[]
if n<m:
A=list(set(num1))
for i in A:
if i in num2:
c.append(i)
else:
A=list(set(num2))
for i in A:
if i in num1:
c.append(i)
return c
# return list(set(num1)&set(num2))集合基本操作一步搞定
自除数 是指可以被它包含的每一位数除尽的数,例如如,128 是一个自除数,因为 128 % 1 == 0,128 % 2 == 0,128 % 8 == 0。还有,自除数不允许包含 0 。给定上边界和下边界数字,输出一个列表,列表的元素是边界(含边界)内所有的自除数。
class Solution(object):
def selfDividingNumbers(self, left, right):
"""
:type left: int
:type right: int
:rtype: List[int]
"""
c=[]
for i in range(left,right+1):
flag=1
for j in str(i):
if j=='0' or int(i)%int(j)!=0:
flag=0
break
if flag==1:
c.append(i)
return c
给定一个整数数组 A,对于每个整数 A[i],我们可以选择任意 x 满足 -K <= x <= K,并将 x 加到 A[i] 中。在此过程之后,我们得到一些数组 B。返回 B 的最大值和 B 的最小值之间可能存在的最小差值。
class Solution(object):
def smallestRangeI(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
if len(A)==1:
return 0
m=max(A)
c=[]
A.remove(m)
if m<=K:
return 0
else:
m=m-K
for j in A:
if m-j<K:
c.append(0)
else:
c.append(m-j-K)
return max(c)
给定一个矩阵 A, 返回 A 的转置矩阵。矩阵的转置是指将矩阵的主对角线翻转,交换矩阵的行索引与列索引。
class Solution(object):
def transpose(self, A):
"""
:type A: List[List[int]]
:rtype: List[List[int]]
"""
c=[]
n=len(A[0])
j=0
while j<n:
d=[]
for i in A:
d.append(i[j])
c.append(d)
j+=1
return c
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行
class Solution(object):
def generate(self, n):
"""
:type numRows: int
:rtype: List[List[int]]
"""
if n==0:
return []
if n==1:
return [[1]]
if n==2:
return [[1],[1,1]]
j=1
c=[1,1]
x=[]
x=[[1],[1,1]]
while j<=n-2:
i=0
d=[]
while i<len(c)-1:
d.append(c[i]+c[i+1])
i+=1
c=[1]+d+[1]
print(c)
x.append(c)
j+=1
return x
给出一个整数数组 A 和一个查询数组 queries。对于第 i 次查询,有 val = queries[i][0], index = queries[i][1],我们会把 val 加到 A[index] 上。然后,第 i 次查询的答案是 A 中偶数值的和
(此处给定的 index = queries[i][1] 是从 0 开始的索引,每次查询都会永久修改数组 A。)
返回所有查询的答案。你的答案应当以数组 answer 给出,answer[i] 为第 i 次查询的答案。
class Solution:
def sumEvenAfterQueries(self, A: List[int], quer: List[List[int]]) -> List[int]:
d = []
l = len(quer)
i = 0
c = [i for i in A if i % 2 == 0]
s=sum(c)
while i < l:
if abs(A[quer[i][1]])%2==1:
if quer[i][0]%2==1:
A[quer[i][1]] += quer[i][0]
s+= A[quer[i][1]]
d.append(s)
else :
A[quer[i][1]] += quer[i][0]
d.append(s)
else:
if abs(A[quer[i][1]])%2==0:
if quer[i][0] % 2==0:
A[quer[i][1]] += quer[i][0]
s+=quer[i][0]
d.append(s)
else:
s = s - A[quer[i][1]]
A[quer[i][1]] += quer[i][0]
d.append(s)
i += 1
return d