求交集算法
集合 — Redis 設計與實現
求交集算法???? SINTER 和 SINTERSTORE 兩個命令所使用的求并交集算法可以用 Python 表示如下:
??? # coding: utf-8
??? def sinter(*multi_set):
??????? # 根據集合的基數進行排序
??????? sorted_multi_set = sorted(multi_set, lambda x, y: len(x) - len(y))
??????? # 使用基數最小的集合作為基礎結果集,有助于降低常數項
??????? result = sorted_multi_set[0].copy()
??????? # 剔除所有在 s[0] 中存在,但在其他集合中不存在的元素
??????? for elem in sorted_multi_set[0]:
??????????? for s in sorted_multi_set[1:]:
??????????????? if (not elem in s) and (elem in result):
??????????????????? result.remove(elem)
??????????????????? break
??????? return result
??? 算法的復雜度為 O(N2) , 執行步數為 S?T , 其中 S 為輸入集合中基數最小的集合, 而 T 則為輸入集合的數量。
總結
- 上一篇: svn 钩子 post-commit 出
- 下一篇: [Winodows图形编程]初识双缓冲技