记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
目录
122.best-time-to-buy-and-sell-stock-ii 买卖股票的最佳时机 II
解题思路:如果数值变小 可以在前一天将股票卖掉
最后添加一个0 可以解决末端问题
def maxProfit(prices):
"""
:type prices: List[int]
:rtype: int
"""
ret = 0
if not prices:
return ret
pre = 0
prices.append(0)
start=prices[pre]
for i in range(1,len(prices)):
if prices[i]<prices[i-1]:
if i-1>pre:
ret += prices[i-1]-prices[pre]
pre= i
start=prices[pre]
return ret
455.assign-cookies 分发饼干
解题思路:个人需求,饼干大小从小到大
遍历饼干
找到最小的小于饼干的人可以添加
def findContentChildren(g, s):
"""
:type g: List[int]
:type s: List[int] 饼干
:rtype: int
"""
p=0
ret = 0
if not s or not g:
return ret
s.sort()
g.sort()
for i in s:
if g[p]<=i:
ret+=1
p+=1
if p==len(g):
break
return ret
860.lemonade-change 柠檬水找零
解题思路:
def lemonadeChange(bills):
"""
:type bills: List[int]
:rtype: bool
"""
dic={}
dic[5]=0
dic[10]=0
for v in bills:
if v==5:
dic[5]+=1
elif v==10:
if dic[5]>0:
dic[5]-=1
dic[10]+=1
else:
return False
else:
if dic[10]>0 and dic[5]>0:
dic[10]-=1
dic[5]-=1
elif dic[5]>2:
dic[5]-=3
else:
return False
return True
874.walking-robot-simulation 模拟行走机器人
解题思路:题目是返回途中最大的欧氏距离平方 并非终点的值
四个方向 用direc来记录往哪边走
commands>0时代表走的步数 需要一步步走 来判断是否会遇到障碍物
障碍物放入set中方便判断
def robotSim(commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
#0:N 1:E 2:S 3:W
direc = 0
x=0
y=0
s = set()
ret=0
def check(pos):
if pos in s:
return True
return False
for v in obstacles:
s.add((v[0],v[1]))
for c in commands:
if c==-1:
direc+=1
if direc>3:
direc=0
elif c==-2:
direc-=1
if direc<0:
direc=3
else:
for i in range(c):
if direc==0:
y+=1
if check((x,y)):
y-=1
break
elif direc==1:
x+=1
if check((x,y)):
x-=1
break
elif direc==2:
y-=1
if check((x,y)):
y+=1
break
elif direc==3:
x-=1
if check((x,y)):
x+=1
break
ret = max(ret,x*x+y*y)
return ret
944.delete-columns-to-make-sorted 删列造序
解题思路:1:常规方法 一列列寻找是否符合
2:使用zip(*A)将A解压
def minDeletionSize1(A):
"""
:type A: List[str]
:rtype: int
"""
ret = 0
if not A:
return ret
slen = len(A[0])
for i in range(slen):
pre = 'a'
for j in range(len(A)):
if A[j][i]<pre:
ret+=1
break
else:
pre= A[j][i]
return ret
def minDeletionSize2(A):
"""
:type A: List[str]
:rtype: int
"""
ret = 0
for i in zip(*A):
if list(i)!=sorted(i):
ret+=1
return ret