记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
从尾至前依次相加
def addStrings(num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
ans = ""
add = 0
n,m=len(num1),len(num2)
i,j=n-1,m-1
while i>=0 or j>=0 or add!=0:
x,y = 0,0
if i>=0:
x = int(num1[i])
if j>=0:
y = int(num2[j])
res = x+y+add
add = res//10
ans = str(res%10)+ans
i,j=i-1,j-1
return ans
将区间起始位置和查询数都从小到大排序 不影响结果
区间[l,r]使用(v,r)表示 v为区间长度 r为右侧坐标
使用小顶堆来存储当前已加入区间
对于第i个区间intervals[i]左侧断点小于查询的数值x则将其加入小顶堆
如果堆顶右侧端点小于x则将其弹出
def minInterval(intervals, queries):
"""
:type intervals: List[List[int]]
:type queries: List[int]
:rtype: List[int]
"""
import heapq
n,m=len(intervals),len(queries)
intervals.sort()
li = sorted((x,i) for i,x in enumerate(queries))
ans = [-1]*m
h = []
i =0
for x,ind in li:
while i<n and intervals[i][0]<=x:
a,b = intervals[i]
heapq.heappush(h,(b-a+1,b))
i+=1
while h and h[0][1]<x:
heapq.heappop(h)
if h:
ans[ind]=h[0][0]
return ans
模拟四个方向 判断每次走一步是否遇到障碍物
如果障碍物则不动
def robotSim(commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
step = [[0,1],[1,0],[0,-1],[-1,0]]
d = 0
cx,cy=0,0
m = set([(x[0],x[1]) for x in obstacles])
ans = 0
for c in commands:
if c<0:
if c==-1:
d+=1
else:
d-=1
d%=4
else:
for i in range(c):
if (cx+step[d][0],cy+step[d][1]) in m:
break
cx,cy=cx+step[d][0],cy+step[d][1]
ans = max(ans,cx*cx+cy*cy)
return ans
子数组有两种情况
一种是不成环 在数组内部 该子数组为最大子数组和
一种是成环 子数组在数组头部和尾部 这中间部分为数组最小子数组和
记录最大子数组和maxs,最小子数组和mins
ans = max(maxs,total-mins)
def maxSubarraySumCircular(nums):
"""
:type nums: List[int]
:rtype: int
"""
total = sum(nums)
curmax,curmin = 0,0
maxs,mins = nums[0],nums[0]
for num in nums:
curmax = max(curmax+num,num)
curmin = min(curmin+num,num)
maxs = max(maxs,curmax)
mins = min(mins,curmin)
if maxs>0:
return max(maxs,total-mins)
else:
return maxs
yi+yj+|xi-xj|=(-xi+yi)+(xj+yj)
list存储(-x+y,x)的值
从头遍历points 去除不满足xj-xi<=k的点
def findMaxValueOfEquation(points, k):
"""
:type points: List[List[int]]
:type k: int
:rtype: int
"""
import collections
ans = float("-inf")
l = collections.deque()
for x,y in points:
while l and x-l[0][1]>k:
l.popleft()
if l:
ans = max(ans,x+y+l[0][0])
while l and y-x>=l[-1][0]:
l.pop()
l.append([y-x,x])
return ans
依次遍历
如果收到10元判断是否有5元
如果收到20元判断是否有10+5或者5*3
def lemonadeChange(bills):
"""
:type bills: List[int]
:rtype: bool
"""
five,ten = 0,0
for v in bills:
if v==5:
five+=1
elif v==10:
if five>0:
five-=1
ten+=1
else:
return False
else:
if ten>0 and five>0:
ten-=1
five-=1
elif five>=3:
five-=3
else:
return False
return True
将水装满
从左到右 记录遇到的最高的墙 让水往左流走
从右往左 记录遇到的最高的墙 让水往右流走
计算最后留下的水
def trap(height):
"""
:type height: List[int]
:rtype: int
"""
n=len(height)
ans = [float("inf")]*n
left = 0
right = 0
for i in range(n):
ans[i] = max(height[i],min(ans[i],left))
ans[n-1-i] = max(height[n-1-i],min(ans[n-1-i],right))
left = max(left,height[i])
right = max(right,height[n-1-i])
return sum(ans)-sum(height)