数据流小问题--find the missing elements
来源:互联网 发布:中国迁都 知乎 编辑:程序博客网 时间:2024/05/21 09:01
这是关于数据流的一个有趣的小问题。问题可以定义为:整个数据流里的元素为1到n的排列(无序),假设移除了k个数,如何找出这k个数。要求使用尽可能少的空间。而且只能顺序扫描数据一次。
对于这个问题,如果没有空间的限制,我们可以使用bitmap轻松搞定,bitmap使用n位即可,扫描到每个元素i,就把第i位设为1,最后结束后值为0的那些位置序号找出来就是所求结果,空间复杂度为O(n)。这个问题时间复杂度肯定是O(n),但在空间复杂度上仍可改进。我们从k=1和k=2这特殊情况开始讨论,然后给出这个问题的通用解决方法。
一、k=1
假设是1到n的排序,是中移除其中一个元素构成的元素,。如何找出移除的那个元素i,也就是找出,但是。
对于这个问题,应该比较容易想出来如下方法来进行计算。我们知道中元素总和为,而中元素总和为。我们只需要统计出流中元素总和即可。这时候我们算法中保存的最大的数字为n*(n+1)/2,需要位来保存,所以空间复杂度为。
二、k=2
该种情况就是数据流中原本n个元素,移除了两个元素,还剩n-2个元素和。按照第一节中的思路,我们可以求出移除元素的和以及平方和,然后通过解方程来获得最终答案。具体来说,我们首先计算:
,
我们在遍历每个元素的时候,进行:
,
当遍历完整个数据流后,我们可得:
,
通过解方程组即可得出:
,。
我们需要保存和两个变量。需要 ,需要,总共需要位保存。
三、k>=3
该种情况下我们可以将k=2时的解决思路进行拓展。我们首先可以使用第二节中的方法得到移除元素的和、平方和,一直到k次方的和。
另外:
通过newton identities,可有由和表示。到其实就是展开后到x的系数以及常数项(的绝对值)。的解是到。
关于newton identities可参看:
http://en.wikipedia.org/wiki/Newton%27s_identities#Formulation_in_terms_of_symmetric_polynomials
- 数据流小问题--find the missing elements
- Find the missing numbers
- Find the missing letter
- *[Lintcode]Find the Missing Number
- Find K Closest Elements问题及解法
- Q5.7 Find the missing number
- C/C++ Find the missing number
- lintcode Find the Missing Number II
- lintcode-196. Find the Missing Number
- Find the elements in the set that appears only once
- 9.1-2 Find the second smallest of n elements.
- PIQ59: Find the missing number in the increasing sequence
- Find the two non-repeating elements in an array of repeating elements
- Find the missing integer from 0 to n
- Find out the missing indexes and their usefulness
- Find the missing integer----programming pearls(second chapter)
- 寻找数组中缺少的整数(Find the missing integer)
- LintCode --find-the-missing-number(寻找缺失的数)
- 前端新技术以及网站整理汇总
- springmvc + mybatis + mysql搭建感想
- PostgreSQL错误处理“operator does not exist: character varying = bytea at character”
- 邢台治自闭症好的yiyuan
- sso-cas全攻略(java版)------部署cas server端应用
- 数据流小问题--find the missing elements
- 邢台治自闭症的最好的yiyuan
- 第五章 串和KMP匹配算法
- Count Primes
- 邢台治自闭症的yiyuan
- SAT词汇背诵需“点面结合”
- C++ 8.1 面向对象的标准库(未完)
- 邢台治自闭症最好的yiyuan是哪家
- 第43讲--项目一--由键盘到文件