This is a demo task.
Write a function:
int solution(int A[], int N);
that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.
For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.
For another example, given A = [1, 2, 3], the function should return 4.
Given A = [−1, −3], the function should return 1.
Assume that:
- N is an integer within the range [1..100,000];
- each element of array A is an integer within the range [−1,000,000..1,000,000].
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).
// you can write to stdout for debugging purposes, e.g.
// printf("this is a debug message\n");int solution(int A[], int N) {
// write your code in C99 (gcc 6.2.0)
int i,j,k,temp;
for(i=0;i<N-1;i++) {
k=i; /*给记号赋值*/
for(j=i+1;j<N;j++)
if(A[k]>A[j]) k=j; /*是k总是指向最小元素*/
if(i!=k) { /*当k!=i是才交换,否则a[i]即为最小*/
temp=A[i];
A[i]=A[k];
A[k]=temp;
}
}
for(i=0;i<=N;i++)
{ if(A[0]<1) return 1;
if(A[i]!=i+1&&A[i+1]!=i+1) return i+1;
}
}