# 41 这是我见过为数不多的hard题这么简单的....
class Solution:
def firstMissingPositive(self, nums):
if not nums:
return 1
max_num = max(nums)
if max_num < 0:
return 1
res = 1
while res < max_num:
if res not in nums:
return res
res += 1
return max_num + 1
# 42
class Solution:
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left, right = 0, len(height) - 1
left_max, right_max = 0, 0
res = 0
while left < right:
if height[left] < height[right]:
if height[left] >= left_max:
left_max = height[left]
else:
res += left_max - height[left]
left += 1
else:
if height[right] >= right_max:
right_max = height[right]
else:
res += right_max - height[right]
right -= 1
return res
# 43 作弊 and 正常
class Solution:
def multiply(self, num1,num2):
return str(int(num1) * int(num2))
class Solution:
def multiply(self, num1,num2):
n1 , n2 = 0 , 0
for i in num1:
n1 = n1 * 10 + int(i)
for i in num2:
n2 = n2 * 10 + int(i)
return str(n1 * n2)
# 44
class Solution:
def isMatch(self, s: str, p: str) -> bool:
tmpp = ""
for i, char in enumerate(p):
if p[i] != "*":
tmpp += p[i]
else:
if i == 0 or p[i] != tmpp[-1]:
tmpp += "*"
p = tmpp[:]
memo = {}
def find(i, j):
if (i, j) not in memo:
ans = False
if j == len(p):
ans = i == len(s)
elif i < len(s):
if p[j] in [s[i], "?"]:
ans = find(i + 1, j + 1)
elif p[j] == "*":
ans = find(i, j + 1) or find(i + 1, j)
elif p[j] == "*":
ans = find(i, j + 1)
memo[i, j] = ans
return memo[i, j]
return find(0, 0)
# 45
class Solution:
def jump(self, nums):
count = 0
count_end = 0
count_far = 0
for i in range(len(nums) - 1):
count_far = max(count_far , nums[i] + i)
if count_end == i:
count += 1
count_end = count_far
return count
# 46
class Solution:
def permute(self,nums):
res = []
def dfs(tmp , num):
if not num:
res.append(tmp)
for idx , val in enumerate(num):
dfs(tmp + [val] , num[:idx] + num[idx + 1:])
dfs([] , nums)
return res
# 47 跟上题一样 只不过有重复项要去除
class Solution:
def permuteUnique(self,nums):
nums.sort()
res = []
def dfs(tmp , num):
if not num:
res.append(tmp)
for idx , val in enumerate(num):
if idx == 0 or num[idx] != num[idx - 1]:
dfs(tmp + [val] , num[: idx] + num[idx + 1:])
dfs([] , nums)
return res
# 48 两步走 先对称再翻过来
class Solution:
def rotate(self, matrix: List[List[int]]) -> None:
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n):
for j in range(i + 1 , n):
matrix[i][j] , matrix[j][i] = matrix[j][i] , matrix[i][j]
for i in range(n):
matrix[i] = matrix[i][::-1]
# 49
class Solution:
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dict = {}
for item in strs:
key = tuple(sorted(item))
dict[key] = dict.get(key, []) + [item]
return list(dict.values())
# 50 搞那么多小数点的数纯粹谢斌人
class Solution:
def myPow(self,x,s):
def S(n):
if n == 0:
return 1
y = S(n//2)
return y * y if n % 2 == 0 else y * y * x
return S(s) if s >= 0 else 1.0 / S(-s)