记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
目录
12/13 807. 保持城市天际线
找出每一行 每一列的最大高度
对于位置i,j 最大高度为min(第i行的max,第j列的max)
def maxIncreaseKeepingSkyline(grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n,m = len(grid),len(grid[0])
col,row = [0]*m,[0]*n
for i in range(n):
for j in range(m):
row[i] = max(row[i],grid[i][j])
col[j] = max(col[j],grid[i][j])
ans = 0
for i in range(n):
for j in range(m):
new = min(row[i],col[j])
ans += new-grid[i][j]
return ans
12/14 630. 课程表 III
将截止期限日期从小到大排序
将耗时放入大顶堆中 如果当前耗时无法满足 但是比堆中最大值小时 进行替换
def scheduleCourse(courses):
"""
:type courses: List[List[int]]
:rtype: int
"""
import heapq
l=[]
heapq.heapify(l)
courses.sort(key = lambda x:x[1])
now = 0
for d,last in courses:
if now+d<=last:
now +=d
heapq.heappush(l,-d)
elif len(l)>0 and -l[0]>d:
now = now-l[0]-d
heapq.heapreplace(l,-d)
return len(l)
12/15 851. 喧闹和富有
根据规定 自己必定满足要求
m[i]记录所有比i富有的编号
深搜
对于i 初始化为自身
搜索所有比i富有的人j(确保所有j都已找到最安静的人)
找到最安静的人
dfs用来确定编号num的结果
def loudAndRich(richer, quiet):
"""
:type richer: List[List[int]]
:type quiet: List[int]
:rtype: List[int]
"""
from collections import defaultdict
m = defaultdict(list)
for x,y in richer:
m[y].append(x)
n = len(quiet)
ans = [-1]*n
def dfs(num):
if ans[num]!=-1:
return
ans[num]=num
for i in m[num]:
dfs(i)
if quiet[ans[i]]<quiet[ans[num]]:
ans[num] = ans[i]
for i in range(n):
dfs(i)
return ans
12/16 1610. 可见点的最大数目
使用反切atan代表点与loc的角度 [-π,π] 将所有点+2π 可以连接-π与π间的区域
对角度进行排序 滑动窗口进行判断最多有几个点
特殊考虑与loc重合点
import math
def visiblePoints(points, angle, location):
"""
:type points: List[List[int]]
:type angle: int
:type location: List[int]
:rtype: int
"""
same = 0
deg = []
for p in points:
if p==location:
same+=1
else:
deg.append(math.atan2(p[1]-location[1],p[0]-location[0]))
deg.sort()
n = len(deg)
deg += [v+2*math.pi for v in deg]
maxc = 0
angdeg = angle*math.pi/180
r = 0
for l in range(n):
while r<2*n and deg[r]<=deg[l]+angdeg:
r+=1
maxc = max(maxc,r-l)
return maxc+same
12/17 1518. 换酒问题
模拟
empty代表空瓶数量
new 代表当前空瓶能够换的酒数量
空瓶每次更新
def numWaterBottles(numBottles, numExchange):
"""
:type numBottles: int
:type numExchange: int
:rtype: int
"""
ans = numBottles
empty = numBottles
while empty>=numExchange:
new = empty//numExchange
ans += new
empty = empty%numExchange + new
return new
12/18 419. 甲板上的战舰
寻找每艘战舰的左上起始点 每个起始点标记一艘
def countBattleships(board):
"""
:type board: List[List[str]]
:rtype: int
"""
n,m = len(board),len(board[0])
ans =0
for i in range(n):
for j in range(m):
if board[i][j]=='X' and (board[i-1][j]=='.' or i==0) and (board[i][j-1]=='.' or j==0):
ans +=1
return ans
12/19 997. 找到小镇的法官
m[i]记录i被多少人相信
ub记录不相信其它人的人
def findJudge(n, trust):
"""
:type n: int
:type trust: List[List[int]]
:rtype: int
"""
from collections import defaultdict
m = defaultdict(int)
ub = set(list(range(1,n+1)))
for a,b in trust:
m[b]+=1
if a in ub:
ub.remove(a)
if len(ub)==1:
num = ub.pop()
if m[num]==n-1:
return num
return -1