我试图分析一个算法,用5个步骤来估计它的时间效率。
五个步骤是:
算法是:
Algorithm UniqueElements (A[0 … n-1)
– //Check whether all the elements in a given array are
distinct
– //Input: an array A[0 … n]
– //Output: returns “true” if all the elements in A are
distinct and “false” otherwise
for i ← 0 to n - 2 do
for j ← i + 1 to n - 1 do
– If A[i] = A[j] return false
return true我解决这个问题的方法是:

我做得对吗?
发布于 2022-07-02 10:19:03
- The best case is when the first two elements are equal then Θ(n)- The worst case is if array elements are unique then all sequences of the for loops are executed- Cworst(n) = ∑i=0n-2∑j=i+1n-1 1- Cworst(n) = ∑i=0n-2[(n-1) - (i+1) + 1] = ∑i=0n-2[n-1- i] = ∑k=n-11k where k = n - i -1- Cworst(n) = ∑k=1n-1k = (n-1)(n-1+1)/2 = n(n-1)/2 ε Θ(n2)注意:对于唯一的数组,有一个最小的n(n-1)/2比较。这有必要吗,有更好的算法吗?
是的,我们可以提前排序。
https://stackoverflow.com/questions/41949704
复制相似问题