今天在学校老师要求我们实现一个删除重复项的算法。这并不难,每个人都想出了以下解决方案(伪代码):
for i from 1 to n - 1
for j from i + 1 to n
if v[i] == v[j] then remove(v, v[j]) // remove(from, what)
next j
next i
这个算法的计算复杂度是 n(n-1)/2
。(我们现在还在上高中,并没有讲过大O符号,但这似乎是 O(n^2)
)。这个解决方案看起来很丑陋,而且当然很慢,所以我试图编写一个更快的代码:
procedure binarySearch(vector, element, *position)
// this procedure searches for element in vector, returning
// true if found, false otherwise. *position will contain the
// element's place (where it is or where it should be)
end procedure
----
// same type as v
vS = new array[n]
for i from 1 to n - 1
if binarySearch(vS, v[i], &p) = true then
remove(v, v[i])
else
add(vS, v[i], p) // adds v[i] in position p of array vS
end if
next i
这样vS
数组将包含我们已经经过的所有元素。如果元素v[i]
在这个数组中,那么它就是一个重复元素,需要被删除。二分查找的计算复杂度是log(n)
,主循环(第二个代码段)的复杂度是n
。因此,如果我没错的话,整个CC的复杂度为n*log(n)
。
然后我又想到了使用二叉树,但是我无法实现。
基本上我的问题是:
- 我的CC计算正确吗?(如果不正确,为什么?)
- 是否有更快的方法?
谢谢
vS
的类型是什么?add
函数具体做什么? - Robin Green