It happened a little later. I see many languages ββbesides the C90
. Like many, I found a solution by creating a secondary array. I used a typical calloc
and then free
. My first solution is similar to others posted:
int solution(int X, int A[], int N) { int *n = calloc(X, sizeof(*A)); int index; for (index = 0; index < N; index++) { if (n[A[index] - 1] == 0) { n[A[index] - 1] = 1; if (--X == 0) { free(n); return index; } } } free(n); return -1; }
I realized that I could leave without a second array at all, since we are dealing with significant integers, and the codility
site also says Elements of input arrays can be modified
. He also says each element of array A is an integer within the range [1..X]
. Since the original input array A
will always have positive numbers, I can use this to my advantage. I can use the signed int
bit in the int A[]
array to indicate that I have already seen the specific position of the sheet (or not). The new version of the code uses the abs
function to process the absolute value in each element of the array for indexing purposes. I set the sign bit to indicate that I have already visited a specific position of the sheet, and I check the actual value by index without using abs
to find out if I have already visited the position. My final decision looked like this:
int solution(int X, int A[], int N) { int index; int leaftimeidx; for (index = 0; index < N; index++) { leaftimeidx = abs(A[index]) - 1; if (A[leaftimeidx] > 0) { A[leaftimeidx] *= -1; if (--X == 0) return index; } } return -1; }
Both versions of my solution passed all the tests.
source share