" 1 2" Stream API, , . , n × m.
, , int 2 ², () int. long , .
, :
public static long smallestDistance(List<Integer> list1, List<Integer> list2) {
int[] list2Sorted = list2.stream().mapToInt(Integer::intValue).sorted().toArray();
if(list2Sorted.length == 0) throw new IllegalArgumentException("list2 is empty");
long smallest = Long.MAX_VALUE;
for(int i: list1) {
int pos = Arrays.binarySearch(list2Sorted, i);
if(pos >= 0) return 0;
pos ^= -1;
if(pos < list2Sorted.length) {
long d = Math.abs(list2Sorted[pos] - (long)i);
if(d < smallest) smallest = d;
}
if(pos > 0) {
long d = Math.abs(list2Sorted[pos-1] - (long)i);
if(d < smallest) smallest = d;
}
}
if(smallest == Long.MAX_VALUE) throw new IllegalArgumentException("list1 is empty");
return smallest;
}
, . , O(n×m) ( ) O((n+m)×log(m)) ( ). , , .
, :
List<Integer> list1
= IntStream.range(0, 100000).mapToObj(i -> i*2).collect(Collectors.toList());
List<Integer> list2
= IntStream.range(0, 100000).mapToObj(i -> i*2+1).collect(Collectors.toList());
, , .