set与unordered_set

使用set

  • 我们需要有序数据(不同元素)。
  • 我们将不得不打印/访问数据(按排序顺序)。
  • 我们需要元素的前任/后继。

使用unordered_set

  • 我们需要保留一组不同的元素,并且不需要排序。
  • 我们需要单元素访问,即无遍历。

示例:

leetcode
1376.Time Needed to Inform All Employees

class Solution {
public:
    int numOfMinutes(int n, int headID, vector<int>& manager, vector<int>& informTime) {
        map<int, vector<int>> m_es;
        for(int i = 0; i < manager.size(); i++){
            if(m_es.find(manager[i])==m_es.end()){
                vector<int> x;
                m_es[manager[i]] = x;
            }
            m_es[manager[i]].push_back(i);
        }
        
        unordered_set<int> visited; // 这里,如果使用set会超时  
        queue<int> q;
        q.push(headID);
        visited.insert(headID);
        int ans = 0;
        while(!q.empty()){
            int boss = q.front();
            q.pop();
            for(auto next:m_es[boss]){
                if(visited.count(next)!=0){
                    continue;
                }
                q.push(next);
                visited.insert(next);
                informTime[next] += informTime[boss];
            }
            
            ans = max(informTime[boss], ans); 
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/jiahangok/p/13744186.html