Weekly Contest 313
Problem A
Number of Common Factors
思路
数据范围小,直接暴力就完事了
代码
class Solution:
def commonFactors(self, a: int, b: int) -> int:
t = []
for i in range(1,min(a,b)+1):
if a%i==0 and b%i==0:
t.append(i)
return len(t)
Problem B
Maximum Sum of an Hourglass
思路
数据范围也挺小的,暴力就完事了
代码
class Solution:
def maxSum(self, grid: List[List[int]]) -> int:
ans = 0
n = len(grid)
m = len(grid[0])
for i in range(0,n-2):
for j in range(0,m-2):
t = grid[i][j]+grid[i+2][j]
t+=grid[i][j+1]+grid[i+1][j+1]+grid[i+2][j+1]
t+=grid[i][j+2]+grid[i+2][j+2]
ans = max(ans,t)
return ans
Problem C
Minimize XOR
思路
转二进制算一下两个数各有多少1,构造结果,优先把1分配到num1的1的位置,多的1再从低到高分配,写的有点拖沓
代码
import numpy as np
class Solution:
def minimizeXor(self, num1: int, num2: int) -> int:
a,b,c = np.zeros(32,dtype=np.int),np.zeros(32,dtype=np.int),np.zeros(32,dtype=np.int)
t = 0
c1,c2 = 0,0
t1,t2 = num1,num2
while num1!=0:
a[t] = num1%2
if a[t]==1:
c1+=1
num1 = num1//2
t+=1
t = 0
while num2!=0:
b[t] = num2%2
if b[t]==1:
c2+=1
num2 = num2//2
t+=1
if c1==c2:
return t1
l = 31
while l>=0 and a[l] == 0:
l-=1
while l>=0 and c2!=0:
if a[l]==1:
c[l]=1
c2-=1
l-=1
l = 0
while c2!=0:
if c[l]==0:
c[l]=1
c2-=1
l+=1
l = 31
# print(c)
while l>=0 and c[l]==0:
l-=1
t = 0
while l>=0:
# print(l)
t = (t<<1)+c[l]
# print(t)
l-=1
return t
Problem D
Maximum Deletions on a String
思路
数据范围小,暴力也能过,大致就是枚举长度做DFS
代码
class Solution:
def deleteString(self, s: str) -> int:
if (len(set(s)) == 1): return len(s)
self.memo = {}
return self.helper(s) + 1
def helper(self, s):
# print(s)
if s in self.memo:
return self.memo[s]
total = 0
for i in range(1, len(s) // 2 + 1):
if s[:i] == s[i: i * 2]:
total = max(total, self.helper(s[i:]) + 1)
self.memo[s] = total
return self.memo[s]
总结
出了三题,最后一题没整明白,没想到大家都是n^3我循环DP过不了 它DFS能过
标签:return,Contest,313,self,int,while,grid,c2,Weekly From: https://www.cnblogs.com/baihualiaoluan/p/16770512.html