Ale*_*rov 5 language-agnostic arrays algorithm hashmap binary-search-tree
我有一组N个不同的数字经常变化.每次更改后,两个或更多数字都有可能变得相等,我不希望这样.数字N可以与最大可能整数一样大.知道经常发生变化,我不想在每次更改后将每个数字与其余数字进行比较.
如何快速查找阵列中是否至少有2个相等的数字?
前者将为您提供O(log(n))平均操作,后者 - O(1);实际结果将取决于您拥有哪种类型的流(数字是随机的吗?增加吗?遵循奇怪的不明显的模式?)
如果您决定采用 BST,请记住您必须保持平衡。
(defparameter *my-data-array* (make-array 100000))
;; fill *my-data-array*
(defparameter *my-data-table*
(let ((ht (make-hash-table)))
(loop for v across *my-data-array*
do (incf (gethash v *my-data-table* 0)))
ht))
(defun modify-data-array (pos new-value)
(let* ((old-value (aref *my-data-array* pos))
(old-count (decf (gethash old-value *my-data-table*)))
(new-count (incf (gethash new-value *my-data-table* 0))))
(setf (aref *my-data-array* pos) new-value)
(case old-count
(0 ; old-value is now not in the array
...)
(1 ; old-value is now unique
...)
(t ; old-value is still not unique
...))
(case new-count
(1 ; new-value was not in the array before
...)
(2 ; new-value was unique before, but not anymore
...)
(t ; new-value was not unique
...))))
Run Code Online (Sandbox Code Playgroud)