[英]Quickly finding if there are 2 or more equal numbers
我有一組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
...))))
作為變體,您可以使用Bloom過濾器 。 它允許測試是否已添加給定數字。 但可能存在誤報誤差。 另一方面,布隆過濾器具有空間效率和快速性,並允許您保留陣列。 如果你重復數字稀少,布隆過濾器算法將對你有用,否則你必須經常在線性時間重新測試數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.