[LeetCode]743. Network Delay Time

栏目: 编程工具 · 发布时间: 7年前

内容简介:There areGivenNow, we send a signal from a certain node

原题

There are N network nodes, labelled  1 to  N .

Given times , a list of travel times as  directed edges  times[i] = (u, v, w) , where  u is the source node,  v is the target node, and  w is the time it takes for a signal to travel from source to target.

Now, we send a signal from a certain node K . How long will it take for all nodes to receive the signal? If it is impossible, return  -1 .

Note:

  1. N  will be in the range  [1, 100] .
  2. K  will be in the range  [1, N] .
  3. The length of  times  will be in the range  [1, 6000] .
  4. All edges  times[i] = (u, v, w)  will have  1 <= u, v <= N  and  1 <= w <= 100 .

题解

Dijskra

本题是典型的求解最短路径的问题,我们可以用Dijsktra方法进行求解。

Dijskra原理见: https://www.youtube.com/watch?v=NLp9C7AvJhk&t=524s

维基百科: https://zh.wikipedia.org/zh/%E6%88%B4%E5%85%8B%E6%96%AF%E7%89%B9%E6%8B%89%E7%AE%97%E6%B3%95

代码

typedef pair<int, int> pii;

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int N, int K) {
        vector<vector<pii>> nodes(N + 1, vector<pii>{});
        for (auto time : times) {
            nodes[time[0]].push_back(make_pair(time[1], time[2]));
        }
        // declare vars
        priority_queue<pii, vector<pii>, greater<pii> > pq; // pii 0 for city index, 1 for cost time
        pq.push(make_pair(K, 0));
        vector<int> time(N + 1, INT_MAX);
        time[K] = 0;
        while (!pq.empty()) {
            pii node = pq.top();
            pq.pop();
            // update the time for the sub-nodes
            for (auto snode : nodes[node.first]) {
                if (time[snode.first] > time[node.first] + snode.second) {
                    time[snode.first] = time[node.first] + snode.second;
                    // add the valid sub-node to priority_queue
                    pq.push(make_pair(snode.first, time[snode.first]));
                }
            }
        }
        int a = -1;
        for (int i = 1; i < time.size(); ++i) {
            if (a < time[i]) a = time[i];
        }
        return a == INT_MAX ? -1 : a;
    }
};

复杂度分析

E代表times的长度

时间复杂度:O(ElogE)

空间复杂度:O(E + N)

原题: https://leetcode.com/problems/network-delay-time/

文章来源:胡小旭=>  [LeetCode]743. Network Delay Time

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

菜鸟侦探挑战数据分析

菜鸟侦探挑战数据分析

[日] 石田基广 / 支鹏浩 / 人民邮电出版社 / 2017-1 / 42

本书以小说的形式展开,讲述了主人公俵太从大学文科专业毕业后进入征信所,从零开始学习数据分析的故事。书中以主人公就职的征信所所在的商业街为舞台,选取贴近生活的案例,将平均值、t检验、卡方检验、相关、回归分析、文本挖掘以及时间序列分析等数据分析的基础知识融入到了生动有趣的侦探故事中,讲解由浅入深、寓教于乐,没有深奥的理论和晦涩的术语,同时提供了大量实际数据,使用免费自由软件RStudio引领读者进一步......一起来看看 《菜鸟侦探挑战数据分析》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具