继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,尤其是powcai大佬和labuladong大佬,感谢各位大佬
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return bin(x ^ y).count("1")
class Solution:
def minMoves2(self, nums: List[int]) -> int:
mid = sorted(nums)[len(nums)//2]
return sum(abs(num - mid) for num in nums)
# 一行
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
import itertools
return sum(sum(map(lambda x, y: x!=y, row + [0], [0] + row)) for row in itertools.chain(grid, map(list, zip(*grid))))
# 直接遍历
class Solution:
def islandPerimeter(self, grid: List[List[int]]) -> int:
res=0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j]==1:
res+=4
if i-1>=0 and grid[i-1][j]==1:
res-=2
if j-1>=0 and grid[i][j-1]==1:
res-=2
return res
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
if maxChoosableInteger >= desiredTotal: return True
sums = (1+maxChoosableInteger)*maxChoosableInteger // 2
if sums < desiredTotal: return False
if sums == desiredTotal: return maxChoosableInteger&1 == 1
dic = {}
def isWin(nums, tmp):
if nums[-1] >= tmp: return True
seenums = tuple(nums)
if seenums in dic:
return dic[seenums]
for i,num in enumerate(nums):
if not isWin(nums[:i]+nums[i+1:], tmp-num):
dic[seenums] = True
return True
dic[seenums] = False
return False
return isWin(list(range(1, maxChoosableInteger+1)), desiredTotal)
class Solution:
def getMaxRepetitions(self, s1: str, n1: int, s2: str, n2: int) -> int:
dp=[]
for i in range(len(s2)):
start=i
end=0
for j in range(len(s1)):
if s1[j] == s2[start]:
start+=1
if start==len(s2):
start=0
end+=1
dp.append((start,end))
res=0
next=0
for _ in range(n1):
res+=dp[next][1]
next=dp[next][0]
return res//n2
class Solution:
def findSubstringInWraproundString(self, p: str) -> int:
if not p: return 0
hashmap=[0]*26
hashmap[ord(p[0])-ord("a")]=1
prelen=1
for i in range(1,len(p)):
gap=ord(p[i])-ord(p[i-1])
if gap==1 or gap==-25:
prelen+=1
else:
prelen=1
hashmap[ord(p[i])-ord("a")]=max(hashmap[ord(p[i])-ord("a")],prelen)
return sum(hashmap)
class Solution:
def validIPAddress(self, IP: str) -> str:
def isIPv4(s):
try:
return str(int(s)) == s and 0 <= int(s) <= 255
except:
return False
def isIPv6(s):
if len(s) > 4: return False
try:
return int(s, 16) >= 0 and s[0] != '-'
except:
return False
if IP.count(".") == 3 and all(isIPv4(i) for i in IP.split(".")):
return "IPv4"
if IP.count(":") == 7 and all(isIPv6(i) for i in IP.split(":")):
return "IPv6"
return "Neither"
class Solution:
def rand10(self):
ans = 41
while ans >= 40:
ans = (rand7()-1)*7+rand7()-1
return ans%10+1