记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
两种情况 第一种奇数位的小 第二种偶数位的小
从头遍历
def movesToMakeZigzag(nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
ans1,ans2 = 0,0
for i in range(n):
tmp1,tmp2 = 0,0
if i%2==0:
if i>0 and nums[i]>=nums[i-1]:
tmp1 = nums[i]-nums[i-1]+1
if i<n-1 and nums[i]>=nums[i+1]:
tmp2 = nums[i]-nums[i+1]+1
ans1 += max(tmp1,tmp2)
else:
if nums[i]>=nums[i-1]:
tmp1 = nums[i]-nums[i-1]+1
if i<n-1 and nums[i]>=nums[i+1]:
tmp2 = nums[i]-nums[i+1]+1
ans2 += max(tmp1,tmp2)
return min(ans1,ans2)
依次遍历 vlist记录所有出现过的价值
集合统计每个价值的重量和
def mergeSimilarItems(items1, items2):
"""
:type items1: List[List[int]]
:type items2: List[List[int]]
:rtype: List[List[int]]
"""
m = {}
vlist = set()
for v,w in items1:
m[v] = m.get(v,0)+w
vlist.add(v)
for v,w in items2:
m[v] = m.get(v,0)+w
vlist.add(v)
ans = []
for v in sorted(list(vlist)):
ans.append([v,m[v]])
return ans
每行每列依次寻找相连三格最大值
def largestLocal(grid):
"""
:type grid: List[List[int]]
:rtype: List[List[int]]
"""
n = len(grid)
tmp = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(1,n-1):
tmp[i][j] = max(grid[i][j-1],grid[i][j],grid[i][j+1])
ans = [[0]*n for _ in range(n)]
for i in range(n):
for j in range(1,n-1):
ans[j][i] = max(tmp[j][i],tmp[j-1][i],tmp[j+1][i])
return [ans[i][1:n-1] for i in range(1,n-1)]
小数点后一位一位相加 直至超过32位
def printBin(num):
"""
:type num: float
:rtype: str
"""
curr = 1.0
ans = "0."
while len(ans)<32:
curr = curr/2
if num>=curr:
num-=curr
ans+="1"
else:
ans+="0"
if num==0:
return ans
return "ERROR"
map存储所有出现过的名字 并记录其当前编号
def getFolderNames(names):
"""
:type names: List[str]
:rtype: List[str]
"""
ans = []
m = {}
for name in names:
if name not in m:
ans.append(name)
m[name]=1
else:
ind = m[name]
while name+'('+str(ind)+')' in m:
ind+=1
cur = name+'('+str(ind)+')'
ans.append(cur)
m[name] = ind+1
m[cur] = 1
return ans
先统计两数相与能够得到的结果cnt
再依次统计每个数在cnt中有多少能与其相与为0
def countTriplets(nums):
"""
:type nums: List[int]
:rtype: int
"""
cnt = [0]*(1<<16)
for i in nums:
for j in nums:
cnt[i&j] +=1
ans = 0
for num in nums:
target = num ^ 0xffff
s = target
while True:
ans += cnt[s]
s = (s-1)&target
if s==target:
break
return ans
如果4个人的钱小于运行的钱 则必定亏本
依次遍历每个时间点的游客 wait记录当前等待游客数量
ans记录最大利润时的经营时间 cur记录当前利润 maxv记录最大利润
当没有后续游客时 继续考虑等待的游客 每次上4人使得利润最大化
def minOperationsMaxProfit(customers, boardingCost, runningCost):
"""
:type customers: List[int]
:type boardingCost: int
:type runningCost: int
:rtype: int
"""
if 4*boardingCost<runningCost:
return -1
wait = 0
ans = -1
cur = -999
maxv = -999
num = 0
for cus in customers:
wait += cus
tmp = min(4,wait)
wait -=tmp
cur += tmp*boardingCost-runningCost
num +=1
if cur>maxv:
maxv = cur
ans = num
while wait>0:
tmp = min(4,wait)
wait -=tmp
cur += tmp*boardingCost-runningCost
num +=1
if cur>maxv:
maxv = cur
ans = num
return ans