There is a question like this about intersection on SO but it does not help me. I have a strict rule to follow. Original Solution
static int solution(int[] A, int[] B) {
int n = A.length;
int m = B.length;
Arrays.sort(A);
Arrays.sort(B);
int i = 0;
for (int k = 0; k < n; k++) {
if (i < m - 1 && B[i] < A[k]) i += 1;
if (A[k] == B[i]) return A[k];
}
return -1;
}
This solution is correct but not in all situations for example arr1={6,6,6,6} arr2={2,4,5,9,6}
It will not result in 6 So task was to add only two lines of code to make it work. I added this
int[] acopy = Arrays.copyOf(A, A.length);
A = n > m ? A : B;
B = n > m ? B : acopy;
n = A.length;
m = B.length;
As a single line now that task will return 6
But when the array is this
int[] x1 = {0, 2, 7, 10, 23, 345, 56, 456, 767, 56, 6, 80, 6, 65}; int y1[] = {1, 4, 5, 9, 9, 9, 80, 67, 77};
It doesnt return 80 Now I am not sure what i should add , my code should not be changed but a single line of modification can be added.
Like Mis94 said here you only need to increment the index of the side with the lower value and this is my approach to solve this
static int solution(int[] A, int[] B) {
int n = A.length;
int m = B.length;
Arrays.sort(A);
Arrays.sort(B);
int i = 0;
for (int k = 0; k < n; k++) {
if (i < m - 1 && B[i] < A[k]) { i += 1; k--; continue; }
if (A[k] == B[i]) return A[k];
}
return -1;
}
I hope that this follows the instructions