【发布时间】:2012-09-05 13:43:52
【问题描述】:
一个数组 A 在 [0, n-1] 范围内包含 n-1 个唯一整数,也就是说,该范围内有一个数字不在 A 中。设计一个 O(n) 算法来找到该数字.除了数组 A 本身之外,只允许使用 O(1) 额外空间。
这个问题需要一些帮助,
【问题讨论】:
标签: algorithm data-structures big-o
一个数组 A 在 [0, n-1] 范围内包含 n-1 个唯一整数,也就是说,该范围内有一个数字不在 A 中。设计一个 O(n) 算法来找到该数字.除了数组 A 本身之外,只允许使用 O(1) 额外空间。
这个问题需要一些帮助,
【问题讨论】:
标签: algorithm data-structures big-o
给定这些值:一个是0 + 1 + 2 + ... + n-1,另一个是实际元素的总和 - 想想它们之间的区别,一个有什么,另一个没有。确保你知道它,答案是微不足道的。
编辑:(理论评论):
请注意,sum(array) 需要 2*log_2(max(arr)) 位。因此,如果您的元素都是 32 位整数,那么您最多需要 64 位来表示总和。
从纯粹的理论方法 - 它不是O(1)。但是,您可以使用数组本身(它包含更多 2*log_2(max(arr)) 位)来存储总和。
【讨论】:
O(1) 额外的空间。 (如果没有这个假设,我们也可以拟合它,但我们可能需要更多元素)。
使用额外的tmp 变量初始化为-1,然后使用tmp 作为位置n 对数组进行排序:
function find_missing(array)
begin
tmp := -1
i := 0;
while i<length(array)
if (array[i] = -1) or (array[i] = i) then
// either on a cell with the right number or
// a candiate for the missing number, just go on
i := i + 1
else if array[i] = n then
// use tmp as the nth cell
array[i]=tmp
tmp=n
else
// swap the value of the current cell with the value
// of the cell were the value i should be
swap(array, i, array[i])
end if
end while
end
-1 应该指向丢失的数字。
【讨论】:
这是另一种方法:
【讨论】: