当前位置:网站首页>[hero planet July training leetcode problem solving daily] 26th and check the collection
[hero planet July training leetcode problem solving daily] 26th and check the collection
2022-07-26 21:17:00 【Seven water Shuliang】
[ Hero planet July training LeetCode Problem solving daily ] The first 26 Japan Union checking set
daily
- Today, I checked the collection and thought it was the result of the water problem wa Once .
subject
One 、 Interview questions 17.07. Baby's name
link : Interview questions 17.07. Baby's name
1. Title Description

2. Thought analysis
- The question surface is very clear , In fact, it is to search the set and find all the ancestor nodes ( The word with the smallest dictionary order in the same family ), Then the frequency of each number is counted on the ancestors .
- I wa Once it was union Before judging x,y Dictionary sequence , And then put x Merge to y, This is wrong , Because after path compression ,x Our ancestors and y Forefathers' Dictionary preface is not necessarily who is big and who is small , So it's in union Inside :x,y Compare the ancestral dictionary order after all paths are compressed , Then select the direction to merge .
- Because my search set template is array , Therefore, we need to discretize words first , Map to digital subscript and search set , More trouble . Next, I plan to sort out a dictionary based template .
- The actual measurement is not discretized faster .
- Attention should be paid to the dictionary based joint search set ,findfather and union Before , hold x,y all setdefault In itself

3. Code implementation
The original answer
class UnionFind:
def __init__(self,size):
self.fathers = list(range(size))
def find_father(self,x):
return self._zip_find_father(x)
def _zip_find_father(self,x):
fathers = self.fathers
if fathers[x] != x:
fathers[x] = self._zip_find_father(fathers[x])
return fathers[x]
def union(self,x,y):
x = self.find_father(x)
y = self.find_father(y)
if x == y:
return False
if x<y:
x,y=y,x
self.fathers[x] = y
return True
def is_same_father(self,x,y):
return self.find_father(x)==self.find_father(y)
class Solution:
def trulyMostPopular(self, names: List[str], synonyms: List[str]) -> List[str]:
# print(names[0].split('('))
frq = {
}
for name in names:
a = name.split('(')
b = a[1].split(')')
frq[a[0]]=int(b[0])
hashed = sorted(frq.keys())
n = len(hashed)
ans = defaultdict(int)
uf = UnionFind(n)
for s in synonyms:
ss = s.split(',')
a = ss[0].split('(')[1]
b = ss[1].split(')')[0]
x = bisect_left(hashed,a)
y = bisect_left(hashed,b)
if x<n and y <n:
uf.union(x,y)
for a,b in frq.items():
f = uf.find_father(bisect_left(hashed,a))
ans[f] += b
return [f'{
hashed[a]}({
b})' for a,b in ans.items()]
Dictionary based union search set
class UnionFind:
def __init__(self,eles):
self.fathers = {
}
f = self.fathers
for e in eles:
f[e] = e
def find_father(self,x):
f = self.fathers
f.setdefault(x,x)
return self._zip_find_father(x)
def _zip_find_father(self,x):
fathers = self.fathers
if fathers[x] != x:
fathers[x] = self._zip_find_father(fathers[x])
return fathers[x]
def union(self,x,y):
f = self.fathers
f.setdefault(x,x)
f.setdefault(y,y)
x = self.find_father(x)
y = self.find_father(y)
if x == y:
return False
if x<y:
x,y=y,x
self.fathers[x] = y
return True
def is_same_father(self,x,y):
return self.find_father(x)==self.find_father(y)
class Solution:
def trulyMostPopular(self, names: List[str], synonyms: List[str]) -> List[str]:
# Frequency into the dictionary
frq = {
}
for name in names:
a = name.split('(')
b = a[1].split(')')
frq[a[0]]=int(b[0])
# Build and look up
uf = UnionFind(frq.keys())
for s in synonyms:
a,b = s[1:-1].split(',')
uf.union(a,b)
# Build answers
ans = defaultdict(int)
for a,b in frq.items():
f = uf.find_father(a)
ans[f] += b
return [f'{
a}({
b})' for a,b in ans.items()]
边栏推荐
- How to enter the specified user method body when debugging in idea?
- 【问题篇】将集合[‘‘,‘‘]处理成(‘‘,‘‘)
- Test cases should never be used casually, recording the thinking caused by the exception of a test case
- Summary of 4 years of software testing experience and interviews with more than 20 companies after job hopping
- 播报语音 h5 SpeechSynthesisUtterance
- Redis hash和string的区别
- SprinBoot面试题
- [MySQL series] - how much do you know about the index
- Leetcode hash table class
- IT系统为什么需要可观测性?
猜你喜欢

GOM and GEE lander list file encryption tutorial

没有网络怎么配置传奇SF登陆器自动读取列表

牛客刷题——Mysql系列

PLSQL package

Explain the 190 secondary compiler (decoding table) module of SMR laminated hard disk of Western data in detail

idea中设置核心配置文件的模板
![[ffmpeg] add timestamp summary to video files](/img/ae/f3f24d16f5d30c276762163867546d.png)
[ffmpeg] add timestamp summary to video files

We were tossed all night by a Kong performance bug

LeetCode链表问题——19.删除链表的倒数第N个节点(一题一文学会链表)

Set the template of core configuration file in idea
随机推荐
Svn uses fragmented ideas
Pointpillars: fast encoders for object detection from point clouds reading notes
[英雄星球七月集训LeetCode解题日报] 第26日 并查集
Shell function, system function, basename [string / pathname] [suffix] can be understood as taking the file name in the path, dirname file absolute path, and user-defined function
Custom annotation (I)
How to enter the specified user method body when debugging in idea?
LiveDatade的基本使用
Sprinboot interview questions
QT基础第一天 (1)QT,GUI(图形用户接口)开发
leetcode 链表类
Sign up now: July 29 recommendation system summit 2022
微信支付的分账功能介绍
Leetcode linked list problem - 19. Delete the penultimate node of the linked list (learn the linked list with one question and one article)
7-year-old boy playing chess too fast? The robot actually broke its finger
ROS2获取当前系统时间的方法
SSM整合实例
每日练习------有一组学员的成绩,将它们按降序排列,要增加一个学员的成绩,将它插入成绩序列,并保持降序
PointPillars: Fast Encoders for Object Detection from Point Clouds 阅读笔记
Kotlin - coroutinecontext
Leetcode hash table class