我在做一些练习时遇到了这个问题...
给定两个 int 数组 A 和 B,以及一个 int 变量 c,返回满足 a + b <= c 的所有 (a, b) 数对总数,其中 a 来自 A,b 来自 B。
我立刻想到了暴力解法,但是似乎无法想出更好的时间复杂度。我尝试先对数组进行排序,并尝试找到某种模式,但是没有任何进展。我考虑了一个数组包含负数的情况。在这种情况下,我不能只看 A 或 B 中是否有小于 c 的值,因为另一个数组中可能有一个负数,当它们相加时可以得到一个 <= c 的结果。如果您有任何见解、想法或线索,将不胜感激。
import java.util.*;
public class CountPairs {
public static void main(String args[]){
int arrayA[] = {32,45,9,4};
int arrayB[] = {43,457,54,90};
Scanner scan = new Scanner(System.in);
System.out.println("Choose the value that you want to find pairs <= ");
int c = scan.nextInt();
System.out.println("The total number of pairs are : " + pairs(arrayA, arrayB, c));
}
public static int pairs(int A[], int B[], int n) {
int count = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < B.length; j++) {
int total = A[i] + B[j];
if(total <= n)
count++;
}
}
return count;
}
}