gpt4 book ai didi

java - 什么是时间复杂度 O(1) 次,Java 中的 O(n) 次

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:28:33 24 4
gpt4 key购买 nike

我有一个场景- 必须读取两个迭代器并需要将它们添加到列表并返回该列表这里什么是“函数应该在 O(1) 时间内运行”。

如果我的理解是正确的,如果数组有 1 个元素,处理时间应该需要 1 秒,如果它有 100 个元素,那么它也应该需要 1 秒...

我怎样才能在这里实现上面读取和添加到新列表操作的 1 秒算法...

最佳答案

O(1)

O(1) describes an algorithm that will always execute in the same time (or space) regardless of the size of the input data set. O(1) time complexity is also called constant time complexity

独立于列表大小,始终返回第一个元素。

boolean IsFirstElementNull(List<string> elements)
{
return elements[0] == null;
}

O(N)

O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set.

boolean ContainsValue(List<string> elements, string value)
{
foreach (var element in elements)
{
if (element == value) return true;
}

return false;
}

很好的来源herehere

关于java - 什么是时间复杂度 O(1) 次,Java 中的 O(n) 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34130278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com