当前位置:网站首页>Leetcode daily question 2022/7/18-2022/4/24
Leetcode daily question 2022/7/18-2022/4/24
2022-07-23 19:02:00 【alphaTao】
The preliminary problem-solving ideas are recorded And local implementation code ; Not necessarily optimal I also hope you can discuss Progress together
Catalog
7/18 749. Isolate the virus
BFS simulation
Search all areas After encountering virus
Search widely and label the linked viruses with the same label -tag
At the same time, count the number of neighbors that will be affected in the next step in this area
def containVirus(isInfected):
""" :type isInfected: List[List[int]] :rtype: int """
ans = 0
m,n = len(isInfected),len(isInfected[0])
while True:
neighbors = []
firewalls = []
for i in range(m):
for j in range(n):
if isInfected[i][j]== 1:
l = [(i,j)]
tag = len(neighbors)+1
neighbor = set()
fw = 0
isInfected[i][j] = -tag
while l:
tmp = []
for x,y in l:
for mx,my in [(0,1),(1,0),(0,-1),(-1,0)]:
nx,ny = x+mx,y+my
if 0<=nx<m and 0<=ny<n:
if isInfected[nx][ny]==1:
tmp.append((nx,ny))
isInfected[nx][ny] = -tag
elif isInfected[nx][ny]==0:
fw +=1
neighbor.add((nx,ny))
l = tmp[:]
neighbors.append(neighbor)
firewalls.append(fw)
if not neighbors:
break
tag = 0
for i in range(1,len(neighbors)):
if len(neighbors[i])>len(neighbors[tag]):
tag = i
ans += firewalls[tag]
for i in range(m):
for j in range(n):
if isInfected[i][j]<0:
if isInfected[i][j]==-tag-1:
isInfected[i][j] = 2
else:
isInfected[i][j] = 1
for i,nb in enumerate(neighbors):
if i!=tag:
for x,y in nb:
isInfected[x][y] = 1
if len(neighbors)==1:
break
return ans
7/19 731. My schedule II
Line segment tree Dynamic opening point
val Record the number of times each node has
lazy Lazy mark Record the number of times that the child nodes in this node have not been distributed
class MyCalendarTwo(object):
def __init__(self):
self.val = {
}
self.lazy = {
}
def update(self,start,end,l,r,idx,val):
if start>r or end<l:
return
if start<=l and r<=end:
self.val[idx] = self.val.get(idx,0)+val
self.lazy[idx] = self.lazy.get(idx,0)+val
return
mid = (l+r)>>1
self.update(start,end,l,mid,2*idx,val)
self.update(start,end,mid+1,r,2*idx+1,val)
v = max(self.val.get(2*idx,0),self.val.get(2*idx+1,0))
self.val[idx] = self.lazy.get(idx,0)+v
def book(self, start, end):
""" :type start: int :type end: int :rtype: bool """
self.update(start,end-1,0,10**9,1,1)
if self.val.get(1,0)>2:
self.update(start,end-1,0,10**9,1,-1)
return False
return True
7/20 1260. Two dimensional grid migration
mn about grid[i][j] Marked as in+j
Each number moves k Time Find the moved marker bit
def shiftGrid(grid, k):
""" :type grid: List[List[int]] :type k: int :rtype: List[List[int]] """
m,n = len(grid),len(grid[0])
ans = [[0]*n for _ in range(m)]
total = m*n
for i in range(m):
for j in range(n):
loc = (i*n+j+k)%total
x = loc//n
y = loc%n
ans[x][y] = grid[i][j]
return ans
7/21 814. Two fork tree pruning
dfs Check two subtrees
If all subtrees are 0 And is itself 0 return true
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def pruneTree(root):
""" :type root: Optional[TreeNode] :rtype: Optional[TreeNode] """
def check(node):
if not node:
return True
l = check(node.left)
if l:
node.left = None
r = check(node.right)
if r:
node.right = None
if l and r and node.val==0:
return True
return False
if check(root):
return None
return root
7/22 757. Set the intersection size to at least 2
take intervals Sort Press x[0] Ascending x[1] Descending
Make sure x[0] Phase at the same time Back x[1] Included by the previous
Think back and forth
For the interval behind In order to have more intersection with the previous interval
Take the first two numbers as good
Use last1,last2 Record the current top two numbers
For the current interval x Come on
If last2<=x[1] Explain that the two existing numbers are x Inside No need to add
If last1<=x[1] Explain that a number is x Inside Need to add a Add x First number x[0] The optimal It is most likely to be in the previous interval
otherwise It means that there is no number at present x Inside Two need to be added x[0],x[0]+1
def intersectionSizeTwo(intervals):
""" :type intervals: List[List[int]] :rtype: int """
intervals.sort(key=lambda x: (x[0], -x[1]))
ans, n = 0, len(intervals)
last1,last2 = intervals[-1][0],intervals[-1][0]+1
ans = 2
for i in range(n-2,-1,-1):
if intervals[i][1]>=last2:
continue
elif intervals[i][1]>=last1:
last1,last2 = intervals[i][0],last1
ans +=1
else:
last1,last2 = intervals[i][0],intervals[i][0]+1
ans +=2
return ans
7/23 The finger of the sword Offer II 115. Reconstruction sequence
Treat two adjacent points in each subsequence as an edge
Set all entries to 0 Join the queue A topological sort
If there is more than one node in the queue It is not unique
If the queue element is 1 individual Take out Point the number to each node in degrees -1
def sequenceReconstruction(nums, sequences):
""" :type nums: List[int] :type sequences: List[List[int]] :rtype: bool """
from collections import defaultdict
n = len(nums)
inD = [0]*n
m = defaultdict(list)
for s in sequences:
for i in range(len(s)-1):
x,y = s[i],s[i+1]
m[x].append(y)
inD[y-1]+=1
l = [i for i,v in enumerate(inD) if v==0]
while l:
tmp = []
if len(l)>1:
return False
for x in l:
for y in m[x+1]:
inD[y-1]-=1
if inD[y-1]==0:
tmp.append(y)
l = tmp
return True
7/24
边栏推荐
- JUC并发编程【详解及演示】
- 398. 随机数索引-哈希表法
- 基于FPGA的SPI通讯协议实现
- 银行业如何实现数字化转型风口全速启航
- LeetCode 剑指 Offer II 115.重建序列:图解 - 拓扑排序
- Navigation component of jetpack compose uses
- [2013] [paper notes] terahertz band nano particle surface enhanced Raman——
- Error "failed to fetch" XXX "temporary failure resolvingw: some index files failed to download" solution
- ZigBee integrated development environment IAR installation
- OSI模型第一层:物理层,基石般的存在!
猜你喜欢

Modeling at the beginning of learning is very confused, how to learn next generation role modeling?

Foundation of class
![[2018] [paper notes] graphene FET and [2] - Preparation and transfer of graphene](/img/32/c6e4af95baf322adf06bd8ee741b67.png)
[2018] [paper notes] graphene FET and [2] - Preparation and transfer of graphene

图的存储结构与方法(二)

Google is improving the skin color performance in all products and practicing the concept of "image fairness"

opencv(13):cv2.findContours、cv::findContours简要介绍及opencv各版本cv2.findContours函数说明
![[the whole process of Game Modeling and model production] create the game soldier character with ZBrush](/img/35/3be94833b6ff1cd251561fb6d92b1e.png)
[the whole process of Game Modeling and model production] create the game soldier character with ZBrush

Know two things: how does redis realize inventory deduction and prevent oversold?

LeetCode 剑指 Offer II 115.重建序列:图解 - 拓扑排序

银行业如何实现数字化转型风口全速启航
随机推荐
LM393低功耗双电压比较器参数、引脚、应用详解
[attack and defense world web] difficulty four-star 12 point advanced question: cat
JUC concurrent programming [detailed explanation and demonstration]
MySQL [knowing and mastering one article is enough]
LeetCode 0131. 分割回文串
mysql的访问端口是什么意思_数据库端口是什么端口号
SQL statement exercise
Opencv (13): brief introduction to cv2.findcontours, cv:: findcontours and description of cv2.findcontours function in various versions of opencv
What problems do you usually encounter when learning 3D modeling? It's too much
【2018】【论文笔记】石墨烯场效应管及【1】——GFETs的种类和原理,GFETs特性,GFETs在太赫兹中的应用和原理
Emgucv common function function description "suggestions collection"
? The problem of front desk parameter transmission needs to be confirmed
Jumpserver administrator account is locked
手写bind、call、apply其实很简单
Handwriting bind, call, apply is actually very simple
?前台传参的问题待确认
MySql【从了解到掌握 一篇就够】
C # startup program loses double quotation marks for parameters passed. How to solve it?
Tcl 语言之Synopsys Tcl篇(3)(数字IC)
How does Apache, the world's largest open source foundation, work?