algorithm - 复杂性和伪代码解释

标签 algorithm time-complexity

我们有以下伪代码

Input: An array A storing n ≥ 1 integers.
Output: The sum of the elements in A.
s←A[0]
for i←1 to n−1 do
s←s+A[i]
return s

首先,我一直在这样的伪代码中注意到这一点,为什么我们写 for i←1 to n−1 do 而不是例如 i←1 to n dofor i←1 to n+1 do ?

其次,这个的复杂度是 O(n-1) 所以 O(n)..我理解为什么它是 O(n),这就是我看到代码时的想法,但为什么 O(n-1)首先 ?

编辑:我想了解的是我们是如何得到 O(n-1)

最佳答案

算法的复杂度为O(N)。对于计算机 O(N+1) , O(N) , O(N-1) , O(N-2) 几乎相同(尤其是当 N 很大时)。所以每个人都将其近似为 O(N)。 他将 i 设置为 N-1 值,因为数组的起始索引为 0。所以你有:

A[0] , A[1] ...., A[N-1] ---> 数组中的 N 个元素。

关于algorithm - 复杂性和伪代码解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29613082/

相关文章:

java - HashMap 迭代复杂度

python - 我的遗传算法有什么问题

algorithm - 交错两个未排序的数组以获得字典序最大的结果

c - 在c程序中用%20替换空格

java - 如何在Java中将二进制小数转换为十六进制?

python - python中的时空分析

algorithm - 在 log n 时间内从大型排序数组中查找所有唯一元素?

algorithm - 每种算法的最佳时间复杂度要求?

c# - 公式和数学表达式解析器算法

performance - 是否所有算法都以 n 为基数(例如 : k^n) of the same time complexity?