簡體   English   中英

這個算法的復雜度是多少? (bfs,最短)

[英]What 's the complexity of this algorithm ? (bfs, shortest)

這個算法的復雜度是多少? 我想表達 big-O 的復雜性。 我不知道我的生活。

問題: req_skill :所需技能列表 people :第 i 個人 people[i] 包含該人擁有的技能列表。 考慮一個足夠的團隊:一組人員,對於 req_skills 中所需的每個技能,團隊中至少有一個人具有該技能。

示例 1:輸入:req_skills = ["java","nodejs","re​​actjs"], people = [["java"],["nodejs"],["nodejs","re​​actjs"]] 輸出:[0 ,2]

解決方案:


類解決方案:

 def smallestSufficientTeam(self, skills: List[str], people: List[List[str]]) -> List[int]:
    
    # Contains a set with each person containing the skill in the skill
    skill_list: List[Set[str]] = [set() for _ in skills]
        
    # Map w/ skill to index (to fill skill_list easier)
    skill_map: Dict[str, int] = {skill: i for i, skill in enumerate(skills)}
    
    # Fills skill_list with index of skill containing person having skill
    for i, person in enumerate(people):
        for skill in person:
            skill_list[skill_map[skill]].add(i)
    
    # Queue for bfs. Passing in skill_list and current chosen people
    queue: List[Tuple[List[Set[str]], List[int]]] = []
    queue.append((skill_list, []))
    
    while queue != []:
        top_skill_set, top_people = queue.pop(0)
        
        # Picks skill w/ smallest number of people involved, and 
        for person in list(min(top_skill_set, key=len)):
            # Eliminates all skills that "person" has
            new_skill_list = [skill for skill in top_skill_set 
                              if person not in skill]
            
            if new_skill_list == []:
                # If no more skills left, this is shortest group yet
                # Note: Because this is a BFS, this will always be shortest
                return top_people + [person]
            else:
                # Add new_skill_list to queue
                queue.append((new_skill_list, top_people + [person]))
                
    return []  # If no solution exists, return empty array

問題: https ://leetcode.com/problems/smallest-sufficient-team/ 代碼: https ://leetcode.com/problems/smallest-sufficient-team/discuss/1402490/Python-Solution-(24ms-beating-100 )

非常感謝您。

因為你在做 BFS。 實際運行時間為 O(V + E),其中 V 是頂點,E 是邊,因為每個都計算一次。

但是,取決於 E(在這種情況下可能是技能),最好的情況是 O(1),最壞的情況是 O(V^2) - BFS 是二叉樹,因此最多兩個連接

看看這些來源(它們更詳細):

https://en.wikipedia.org/wiki/Time_complexity https://www.comp.nus.edu.sg/~cs1020/tut/15s2/tut09ans/T9_ans.pdf

對於 BFS 繪圖: https ://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/?ref=lbp

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM