这是在codility上看到的一个题目:
A non-empty zero-indexed array A consisting of N integers is given. The first covering prefix of array A is the smallest integer P such that 0≤P<N and such that every value that occurs in array A also occurs in sequence A[0], A[1], ..., A[P].
For example, the first covering prefix of the following 5−element array A:
A[0] = 2 A[1] = 2 A[2] = 1A[3] = 0 A[4] = 1
is 3, because sequence [ A[0], A[1], A[2], A[3] ] equal to [2, 2, 1, 0], contains all values that occur in array A.
Write a function
int solution(int A[], int N);
that, given a zero-indexed non-empty array A consisting of N integers, returns the first covering prefix of A.
Assume that:
- N is an integer within the range [1..1,000,000];
- each element of array A is an integer within the range [0..N−1].
For example, given array A such that
A[0] = 2 A[1] = 2 A[2] = 1A[3] = 0 A[4] = 1
the function should return 3, as explained above.
Complexity:
- expected worst-case time complexity is O(N);
- expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
解题思路:
这个问题就是:在数组A中找到第一个索引p使得子数组A[0...p]中包括数组A中所有不重复的元素。要求的最差时间复杂度和空间复杂度为O(N)。
题目给出了数组A中可能出现的整数的范围[1...1000000],可以申请一个空间(假设名称为space,每个元素为整数)来存储数组A中每个元素出现的次数,空间的元素个数为1000000+1(因为C中数组元素下标是从0开始)。
首先循环将space中的每个元素都初始化为0,表示当前的位置没有元素。然后循环遍历数组A,以数组A中的元素为索引,将space中对应的元素加1。
最后还是循环遍历数组A中的元素,不过这次是从最后一个元素开始。假设当前下标为i,以A[i]为索引的space中对应的元素的值为tmp。如果tmp的值大于1,表示A数组中下标从0到i-1的子数组中仍然存在元素A[i],此时只将space中以A[i]为索引的值减1,继续循环;如果tmp的值为1,则表示A数组中下标从0到i-1的子数组中没有元素A[i],所以此时已经找到,退出循环。
代码实现如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int solution(int A[], int N) {
int *space = NULL;
int size = 1000001;
int i;
space = malloc(sizeof(int) * size);
if (!space ) {
perror("malloc");
return -1;
}
for (i = 0; i < size; ++i) {
space[i] = 0;
}
for (i = 0; i < N; ++i) {
space[A[i]]++;
}
for (i = N - 1; i >= 0; --i) {
if (space[A[i]] == 1) {
break;
}
--space[A[i]];
}
free(space);
return i;
}
int main(void)
{
int A[] = {2, 2, 1, 0, 1, 3, 1, 2, 10};
printf("solution: %d.\n", solution(A, sizeof(A) / sizeof(int)));
return 0;
}