继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,尤其是powcai大佬和labuladong大佬,感谢各位大佬
# 排序,看前面的在不在
class Solution:
def findAllConcatenatedWordsInADict(self, words: List[str]) -> List[str]:
words.sort(key=len)
min_len = max(1, len(words[0]))
prev = set()
res = []
def check(word):
if word in prev: return True
for i in range(min_len, len(word) - min_len + 1):
if word[:i] in prev and check(word[i:]):
return True
return False
for word in words:
if check(word):
res.append(word)
prev.add(word)
return res
class Solution:
def makesquare(self, nums: List[int]) -> bool:
if len(nums) < 4: return False
div, mod = divmod(sum(nums), 4)
if mod != 0: return False
nums.sort(reverse=True)
edges = [0] * 4
def dfs(i):
if i == len(nums):
if len(set(edges)) == 1:
return True
return False
for k in range(4):
if edges[k] + nums[i] > div: continue
edges[k] += nums[i]
if dfs(i + 1): return True
edges[k] -= nums[i]
return False
return dfs(0)
# dp
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[[0] * (n + 1) for _ in range(m + 1)] for _ in range(len(strs) + 1)]
for i in range(1, len(strs) + 1):
ones = strs[i - 1].count("1")
zeros = strs[i - 1].count("0")
for j in range(m + 1):
for k in range(n + 1):
dp[i][j][k] = dp[i - 1][j][k]
if j >= zeros and k >= ones and dp[i][j][k] < dp[i - 1][j - zeros][k - ones] + 1:
dp[i][j][k] = dp[i - 1][j - zeros][k - ones] + 1
return dp[-1][-1][-1]
class Solution:
def findRadius(self, houses: List[int], heaters: List[int]) -> int:
houses.sort()
heaters.sort()
heaters = [float("-inf")] + heaters + [float("inf")]
i = 1
res = 0
for house in houses:
while i < len(heaters) - 1 and house > heaters[i]:
i += 1
res = max(res, min(heaters[i] - house, house - heaters[i - 1]))
return res
class Solution:
def findComplement(self, num: int) -> int:
return 2**(len(bin(num))-2)-num-1
class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
res, n = 0, len(nums)
for i in range(32):
cnt = 0
for j in range(n):
cnt += (nums[j] >> i) & 1
res += (n - cnt) * cnt
return res
# 极坐标
import math
import random
class Solution:
def __init__(self, radius: float, x_center: float, y_center: float):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
def randPoint(self) -> List[float]:
l = self.radius * math.sqrt(random.random())
deg = random.random() * math.pi * 2
x = l * math.cos(deg) + self.x_center
y = l * math.sin(deg) + self.y_center
return [x, y]
# 打表了
class Solution:
def largestPalindrome(self, n: int) -> int:
return [9,987,123,597,677,1218,877,475][n-1]
class Solution:
def medianSlidingWindow(self, nums: List[int], k: int) -> List[float]:
import bisect
arr = []
left = 0
res = []
for right in range(len(nums)):
bisect.insort(arr, nums[right])
while len(arr) > k:
arr.pop(bisect.bisect_left(arr, nums[left]))
left += 1
if len(arr) == k:
res.append((arr[k // 2] + arr[(k - 1) // 2]) / 2.0)
return res