降低这些函数的时间和空间复杂度

发布于 2025-01-16 02:31:03 字数 1095 浏览 3 评论 0原文

在这里,我从列表中生成一个随机数。

/////somecode///////
        randNum = new Random();
        Dictionary = new Dictionary<int, double>();
        List1 = new List<double>();
 /////somecode///////   

public int func1()
{
    double rand = randNum.NextDouble();
    int index = 0;
    foreach (var item in Dictionary)
    {
        if (randomNum <= List1[index])
        {
            return item.Key;
        }
        index++;
    }
    return -1 ;
}

在这里,我给出一个pairList作为参数,将其键和值添加到Dictionary1中。

    public void func2(List<KeyValuePair<string, int>> pairList)
    {
        foreach (var item in pairList)
        {
            if (Dictionary1.TryGetValue(pair.Key, out double value))
            {
                Dictionary1.Remove(item.Key);
                sum -= value;
                SumList.Remove(sum);
            }
            Dictionary1.Add(new KeyValuePair<string, int>(item.Key, item.Value));
            Sum += item.Value;
            SumList.Add(_cdfSum);
        }
    }

如何降低这些函数的时间和空间复杂度?

Here I generate a random number from a list.

/////somecode///////
        randNum = new Random();
        Dictionary = new Dictionary<int, double>();
        List1 = new List<double>();
 /////somecode///////   

public int func1()
{
    double rand = randNum.NextDouble();
    int index = 0;
    foreach (var item in Dictionary)
    {
        if (randomNum <= List1[index])
        {
            return item.Key;
        }
        index++;
    }
    return -1 ;
}

And here I give a pairList as a parameter to add it's keys and values to the Dictionary1.

    public void func2(List<KeyValuePair<string, int>> pairList)
    {
        foreach (var item in pairList)
        {
            if (Dictionary1.TryGetValue(pair.Key, out double value))
            {
                Dictionary1.Remove(item.Key);
                sum -= value;
                SumList.Remove(sum);
            }
            Dictionary1.Add(new KeyValuePair<string, int>(item.Key, item.Value));
            Sum += item.Value;
            SumList.Add(_cdfSum);
        }
    }

How can I reduce the time and space complexity of these functions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文