130-被围绕的区域(python)
#深度优先
class Solution(object):
def solve(self,board):
if not board:return
row=len(board)
col=len(board[0])
def dfs(i,j):
board[i][j]='B'
for x,y in [(-1,0),(1,0),(0,-1),(0,1)]:
tmp_i=i+x
tmp_j=j+y
if 1<=tmp_i<row and 1<=tmp_j<col and board[tmp_i][tmp_j]=='o':
dfs(tmp_i,tmp_j)
for i in range(row):
if board[i][0]=='o':
dfs(i,0)
if board[i][col-1]=='o':
dfs(i,col-1)
for j in range(col):
if board[0][j]=='o':
dfs(0,j)
if board[row-1][j]=='o':
dfs(row-1,j)
for i in range(row):
for j in range(col):
if board[i][j]=='o':
board[i][j]='X'
if board[i][j]=='B':
board[i][j]='o'
131-分割回文串(python)
#回溯
class Solution(object):
def partion(self,s):
res=[]
def helper(s,tmp):
if not s:res.append(tmp)
for i in range(1,len(s)-1):
if s[:i]==s[:i][::-1]:
helper(s[:i],tmp+[s[:i])
helper(s,[])
return res
134-加油站(python)
class Solution(object):
def canCompleteCircuit(self,gas,cos):
n=len(gas)
total_tank,curr_tank=0,0
starting_station=0
for i in range(n):
total_tank+=gas[i]-cos[i]
curr_tank+=gas[i]-cos[i]
if cur_tank<0:
starting_station+=1
curr_tank=0
return starting_station if total_tank>=0 else -1
138-复制待随机指针的链表(python)
#1-1’-2-2’
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
#输入1->2->3->None
#则中间结果为1->1(copy)->2->2(copy)->3->3(copy)->None
#返回1(copy)->2(copy)->3(copy)->none
if not head:
return None
# 第一遍遍历,把每个新生成的结点放在对应的旧结点后面
p = head
while p:
new_node = Node(p.val)
new_node.next = p.next
p.next = new_node
p = new_node.next # 下一个旧结点
# 第二遍修改每个新结点的 next 和 random
p = head
while p:
next_origin = p.next.next # 下一个旧结点备份一下
p.next.next = next_origin.next if next_origin else None # 修改新结点的 next
p.next.random = p.random.next if p.random else None # 修改新结点的 random
p = next_origin # 下一个旧结点
return head.next
140-单词拆分2(python)
#深度优先
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
def dfs(s, memo, wordDict):
if s in memo:
return memo[s]
if s == '':
return []
res = []
for word in wordDict:
if not s.startswith(word):
continue
# 循环到最后而且匹配,则append
if len(word) == len(s):
res.append(word)
# 匹配但是没有循环到最后,于是继续往下,之后需要对返回的结果分别加上当前的word
else:
rest = dfs(s[len(word):], memo, wordDict)
for item in rest:
item = word + ' ' + item
res.append(item)
# 保存当前s的结果
memo[s] = res
return res
res = []
memo = {}
return dfs(s, memo, wordDict)
149-直线上最多的点数(python)
class Solution:
def maxPoints(self, points: List[List[int]]) -> int:
if len(points) <= 2:
return len(points)
maxNum = 0
for i in range(len(points)):
maxNum = max(maxNum,self.find(points[i],points[:i]+points[i+1:]))
return maxNum + 1
def find(self,point,pointList):
memories = {} # 记录pointList中和point相同的点
count = 0 # 记录相同的点
inf = float("inf") # 先判断有没有斜率为无穷的点
for curPoint in pointList:
if curPoint[1] == point[1] and curPoint[0] != point[0]:
memories[inf] = memories.get(inf,0) + 1
elif curPoint[1] == point[1] and curPoint[0] == point[0]:
# 判断有没有相同的点
count += 1
else:
slope = (curPoint[0] - point[0]) / (curPoint[1] - point[1])
memories[slope] = memories.get(slope,0) + 1
if memories:
return count + max(memories.values())
# 找到由point构成的包含最多点的直线中点数
else:
# 如果字典为空,说明pointList中要么没有点,要么都是和point重合的点
return count
150-逆波兰表达式求值(python)
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
symbol = ["+","-","*","/"]
recList = []
if len(tokens) == 0: return 0
for c in tokens:
if c not in symbol:
recList.append(c)
else:
b = int(recList.pop())
a = int(recList.pop())
if c == "+":
recList.append(str(a+b))
elif c == "-":
recList.append(str(a-b))
elif c == "*":
recList.append(str(a*b))
elif c == "/":
recList.append(str(int(a/b)))
return int(recList[0])
162-寻找峰值(python)
#二分查找
class Solution(object):
def findReakElement(self,nums):
l=0
r=len(nums)-1
while l<r:
mid=(l+r)//2
if nums[mid]>nums[mid+1]:
r=mid
else:
l=mid+1
return l
163-分数到小数(python)
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator == 0: return "0"
res = []
# 首先判断结果正负, 异或作用就是 两个数不同 为 True 即 1 ^ 0 = 1 或者 0 ^ 1 = 1
if (numerator > 0) ^ (denominator > 0):
res.append("-")
numerator, denominator = abs(numerator), abs(denominator)
# 判读到底有没有小数
a, b = divmod(numerator, denominator)
res.append(str(a))
# 无小数
if b == 0:
return "".join(res)
res.append(".")
# 处理余数
# 把所有出现过的余数记录下来
loc = {b: len(res)}
while b:
b *= 10
a, b = divmod(b, denominator)
res.append(str(a))
# 余数前面出现过,说明开始循环了,加括号
if b in loc:
res.insert(loc[b], "(")
res.append(")")
break
# 在把该位置的记录下来
loc[b] = len(res)
return "".join(res)
171-Excel表列序号(python)
#倒序计算
class Solution:
def titleToNumber(self, s: str) -> int:
res = 0
bit = 1
for a in s[::-1]:
res += (ord(a) - 64) * bit
bit *= 26
return res
172-阶乘后的零(python)
class Solution:
def trailingZeroes(self, n: int) -> int:
p = 0
while n >= 5:
n = n // 5
p += n
return p
179-最大数(python)
class Solution(object):
def largestNumber(self, nums):
n=len(nums)
s=''
for a in range(0,n-1):
for b in range(a+1,n):
if str(nums[a])+str(nums[b])<str(nums[b])+str(nums[a]):
nums[a],nums[b]=nums[b],nums[a]
for i in nums:
s=s+str(i)
if int(s)==0:return '0'
return s
189-旋转数组(python)
#swap
class Solution(object):
def rotate(self,nums,k):
def swap(l,r):
while l<r:
nums[l],nums[r]=nums[r],nums[l]
l+=1
r-=1
k=k%len(nums)
n=len(nums)
swap(0,n-k-1)
swap(n-k,n-1)
swap(0,n-1)
return nums
130-被围绕的区域(python)
#从低到高检查是不是为1
class Solution:
def reverseBits(self, n):
ans,mask=0,1
for i in range(32):
if n&mask:
ans |= 1<<(31-i)
mask<<=1
return ans
191-位1的个数(python)
class Solution(object):
def hamingweight(self,n):
count=0
while n>0:
n&=(n-1)
count+=1
return count
202-快乐数(python)
class Solution(object):
def ishappy(self,n):
temp=[n]
while n!=1:
a=list(str(n))
for i in a:
n+=pow(int(i),2)
temp.append(n)
if len(temp)!=len(set(temp)):
return False
return True