【发布时间】:2015-03-20 10:58:55
【问题描述】:
给出了一个由 N 个不同整数组成的零索引数组 A。该数组包含[1..(N + 1)] 范围内的整数,这意味着缺少一个元素。
你的目标是找到那个缺失的元素。
写一个函数:
int solution(int A[], int N);
给定一个零索引数组A,返回缺失元素的值。
例如,给定数组 A 使得:
A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5
函数应该返回4,因为它是缺少的元素。
假设:
N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].
复杂性:
expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
它不适用于有两个元素的情况
int solution(vector<int> &A) {
sort(A.begin(), A.end());
int missingIndex = 0;
for (int i = 0; i < A.size(); i++)
{
if ( i != A[i]-1)
{
missingIndex = i+1;
}
}
return missingIndex;
}
【问题讨论】:
-
使用排序将导致不具有所需的最坏情况时间复杂度 O(N)。你必须做一些比这更聪明的事情。就像从元素 1 (A[0]) 开始,获取它的值 (2),到元素 2 (A[1]),将其标记为“已看到”(例如,通过赋予它值 0),对 A 执行相同操作[1]。完成所有这些,扫描阵列并找到未标记为已见的阵列。在时间上应该是 O(n),在空间上应该是 O(1),代价是搞砸了原始数据。不错的谜题,但我现在不想写代码。
-
@ecotax 在这种情况下,排序可以达到
O(N)的复杂性。由于您的值范围有限,因此它适用于计数排序。真正的限制是O(1)空间限制:) -
@fjardon 确实,在这种情况下,您可以使用足够高效的排序算法。此外,Raistmaj 找到了一个更简单/更智能的解决方案。不错。