package com.company;
import java.util.Arrays;
public class Algorithm {
int intersection(int[] arr1, int[] arr2) {
if (arr1.length == 0 || arr2.length == 0) {
throw new RuntimeException("Invalid length");
}
Arrays.sort(arr1);
Arrays.sort(arr2);
int arr1Indx = 0;
int arr2Indx = 0;
while (arr1Indx < arr1.length - 1 && arr2Indx < arr2.length - 1) {
if (arr1[arr1Indx] == arr2[arr2Indx]) {
return arr1[arr1Indx];
} else if (arr1[arr1Indx] > arr2[arr2Indx]) {
arr2Indx++;
} else {
arr1Indx++;
}
}
throw new RuntimeException("no intersection");
}
}
package com.company;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class AlgorithmTest {
@Test
void largestAndSmallest1() {
Algorithm algorithm = new Algorithm();
int[] array1 = new int[]{2, 9, 6, 0, 6, 4, 2};
int[] array2 = new int[]{1, 5, 7, 0, 8, 3, 4};
int intersection = algorithm.intersection(array1, array2);
Assertions.assertEquals(0, intersection);
}
@Test
void largestAndSmallest2() {
Algorithm algorithm = new Algorithm();
int[] array1 = new int[]{10, 3, 5, 5, 0, 1, 10};
int[] array2 = new int[]{1, 7, 2, 8, 3, 4, 5};
int intersection = algorithm.intersection(array1, array2);
Assertions.assertEquals(1, intersection);
}
@Test
void largestAndSmallest3() {
Algorithm algorithm = new Algorithm();
int[] array1 = new int[]{10, 3, 5, 5, 0, 1, -20};
int[] array2 = new int[]{1, 7, 2, 8, 3, 4, 5, -20};
int intersection = algorithm.intersection(array1, array2);
Assertions.assertEquals(-20, intersection);
}
}
plugins {
id 'java'
}
group 'org.example'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
testImplementation('org.junit.jupiter:junit-jupiter:5.6.2')
}
test {
useJUnitPlatform()
}