这看起来与旧问题相似但有所不同。给定一个大小为 n 的数组(允许重复的数字),找到缺失的 2 个数字
**不,它是重复的!给定数组中的某些数字可能是重复的。请参考我帖子底部的示例。谢谢 !!! **
给定一个大小为 n 的数组,其中包含 1 到 n 范围内的数字。除 2 个数字外,每个数字至少出现一次。找出缺失的数字。
例如A = [2, 4, 5, 4, 6, 5],缺少的数字是3和1。
我的解决方案:
用O(n lg n)对A进行排序,然后扫描。
或者,扫描并建立一个新的布尔数组B来标记给定数组中的数字是否出现,例如B[A[i]] = true或false。然后,扫描 bool 数组,找到索引为缺失元素的 false 元素。时间 O(n) 但空间 O(n)。
是否存在时间 O(n) 和空间 O(1) 的解?
注意: 加法和乘法的方法不起作用。
例如,给定 A [2, 3, 2, 3],缺失的数字为:1 和 4。
假设缺失的数字为 x 和 y。
我们不能得到:
x + y = 1 到 n 之和 - A 之和
x * y = 1 到 n 的乘积 / A 的乘积
1 + 4 != 10 - 10
1 * 4 != 24/36
谢谢
Possible Duplicate:
Easy interview question got harder: given numbers 1..100, find the missing number(s)
**No, it is a duplicate !!! some numbers in the given array may be duplicated. Please refer to the example at the bottom of my post. thanks !!! **
Given an array of size n, containing numbers in the range 1 to n. Each number is present at least once except for 2 numbers. Find the missing numbers.
e.g. A = [2, 4, 5, 4, 6, 5], missing numbers are 3 and 1.
My solutions:
sort A with O(n lg n) then scan.
Or, scan and set up a new bool array B to mark whether a number in the given array appears or not, e.g. B[A[i]] = true or false. Then, scan the bool array to the false element whose index is the missing element. Time O(n) but space O(n).
Are there solutions of O(n) in time and O(1) in space ?
Attention:
the method of sum and multiplication does not work.
For example, given A [2, 3, 2, 3], the missing numbers are : 1 and 4.
Suppose missing numbers are x and y.
we cannot get:
x + y = sum of 1 to n - sum of A
x * y = product of 1 to n / product of A
1 + 4 != 10 - 10
1 * 4 != 24/36
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果数据未排序,则无法确保您无需查看每个值即可找到缺失值。因此,最坏的情况是找到它们的时间复杂度为 O(n)。要确定缺少哪些内容,您可以通过计算
n
和sum(1..n)
的阶乘并除以乘积和从您遇到的每个术语的总和中减去。最后,您可以通过求解a + b = 剩余总和
和a * b = 剩余产品
来知道缺少哪些内容。但这是一个作弊行为,因为您实际上是在进行初步的 O(n) 计算,或者进行具有空间影响的表查找。If the data is unsorted, there is no way to assure you can find the missing values without looking at each one. So, worst case would be O(n) to find them. To determine which are missing, you could do it in O(1) by computing the factorial of
n
andsum(1..n)
and dividing out of the product and subtracting from the sum each term you encounter. At the end you'd know which are missing by solving fora + b = remaining sum
anda * b = remaining product
. This is a cheat though since you are essentially doing a preliminary O(n) computation or else a table-lookup which has a space impact.codekaizen 的想法可以进行调整以使其可行:
计算 U = 所有元素的总和,V = 所有元素的平方和。
如果 a 和 b 是缺失元素,我们
将 b = W - a 代入第二个方程,得到
这是 a 的二次方程,您可以求解。
codekaizen's idea can be adapted to make it workable:
Compute U = the sum of all the elements, and V = the sum of squares of all the elements.
If a and b are the missing elements, we have
Substitute b = W - a in the second equation to get
This is a quadratic equation in a, which you can solve.