如何降低带有嵌套循环的C#方法的时间复杂度

时间:2020-09-13 12:01:06

标签: c# big-o

我正在使用Kubernetes C#客户端通过更改具有特定映像名称的容器中的映像标签来修补集群中的部署。

据我所知,我的方法的拳头版本似乎效率不高,具有二次时间复杂度O(n2)。

private List<V1Deployment> UpdateImageTag(string imageName, string tag, List<V1Deployment> deployments)
        {
            var updatedDeployments = new List<V1Deployment>();

            if (deployments?.Count > 0)
            {
                foreach (var deployment in deployments)
                {
                    foreach (var container in deployment?.Spec?.Template?.Spec?.Containers.SkipWhile(x => !x.Image.ToLowerInvariant()
                                                                                                            .StartsWith(imageName.ToLowerInvariant())))
                    {
                        if (container is null)
                        {
                            // Log it and go to the next container.
                            _logger.LogDebug("Deployment {Deployment} has a null container, skipping it.", deployment?.Metadata?.Name);
                            continue;
                        }
                        SetImageTag(tag, container);

                        if (!updatedDeployments.Contains(deployment))
                        {
                            updatedDeployments.Add(deployment);
                        }
                    }
                }
            }

            return updatedDeployments;
        }

如何以更有效的方式实现这一目标?

1 个答案:

答案 0 :(得分:0)

与注释相反,最坏情况下的时间复杂度实际上是import pandas as pd %load_ext google.colab.data_table from sklearn.datasets import load_breast_cancer data = load_breast_cancer() df = pd.DataFrame(data['data'], columns=data['feature_names']) df['target'] = data['target'] df ,其中O(n^2)n的长度。但这不是因为嵌套的deployment;这是因为调用了foreach。实际上,这还比这更糟-复杂度更确切地说是Contains,其中O(m*n^2)是每个部署的容器数,因为m在内部循环中。

这样做(复杂度为Contains,对于输入数据结构来说是最佳的):

O(m*n)