Algorithm 有界平方和算法

Algorithm 有界平方和算法,algorithm,time-complexity,Algorithm,Time Complexity,问题如下: You are given two arrays of integers a and b, and two integers lower and upper. Your task is to find the number of pairs (i, j) such that lower ≤ a[i] * a[i] + b[j] * b[j] ≤ upper. Example: For a = [3, -1, 9], b = [100, 5, -2], lower = 7, an

问题如下:

You are given two arrays of integers a and b, and two integers lower and upper. 
Your task is to find the number of pairs (i, j) such that lower ≤ a[i] * a[i] + b[j] * b[j] ≤ upper.

Example:

For a = [3, -1, 9], b = [100, 5, -2], lower = 7, and upper = 99, the output should be boundedSquareSum(a, b, lower, upper) = 4.
There are only four pairs that satisfy the requirement:
If i = 0 and j = 1, then a[0] = 3, b[1] = 5, and 7 ≤ 3 * 3 + 5 * 5 = 9 + 25 = 36 ≤ 99.
If i = 0 and j = 2, then a[0] = 3, b[2] = -2, and 7 ≤ 3 * 3 + (-2) * (-2) = 9 + 4 = 13 ≤ 99.
If i = 1 and j = 1, then a[1] = -1, b[1] = 5, and 7 ≤ (-1) * (-1) + 5 * 5 = 1 + 25 = 26 ≤ 99.
If i = 2 and j = 2, then a[2] = 9, b[2] = -2, and 7 ≤ 9 * 9 + (-2) * (-2) = 81 + 4 = 85 ≤ 99.
For a = [1, 2, 3, -1, -2, -3], b = [10], lower = 0, and upper = 100, the output should be boundedSquareSum(a, b, lower, upper) = 0.
Since the array b contains only one element 10 and the array a does not contain 0, it is not possible to satisfy 0 ≤ a[i] * a[i] + 10 * 10 ≤ 100.

现在,我知道有一种蛮力方法可以解决这个问题,但是这个问题的最佳解决方案是什么?

使用元素的绝对值对较小的数组进行排序,然后对未排序数组中的每个元素,在排序的数组上对间隔进行二进制搜索。

使用元素的绝对值对较小的数组进行排序,然后,对于未排序数组中的每个元素,二进制搜索已排序数组上的间隔。

可以只对其中一个元素进行排序,然后对未排序数组进行迭代。@。你所说的“搜索区间”是什么意思?@Marko仅以区间的下限lb为例。由于a^2+b^2对于固定的a是单调递增的,当我们沿着排序数组移动时,当前迭代中未排序数组中的元素,因此我们可以使用二进制搜索规则:如果a^2+b^2大于lb,则没有必要查看b的右侧,因为总和将增长,因此我们查看b的左侧部分,类似地,当a^2+b^2小于lb时,再往左看也没有意义了。@Marko我的意思是分别对区间的每个边界进行二进制搜索。然后使用公式right_index-left_index+1计算区间内有多少个数字。知道了,谢谢。那么复杂度将是n*logn?可以只对其中一个进行排序,然后对未排序的一个进行迭代。@。你所说的“搜索区间”是什么意思?@Marko仅以区间的下限lb为例。由于a^2+b^2对于固定的a是单调递增的,当我们沿着排序数组移动时,当前迭代中未排序数组中的元素,因此我们可以使用二进制搜索规则:如果a^2+b^2大于lb,则没有必要查看b的右侧,因为总和将增长,因此我们查看b的左侧部分,类似地,当a^2+b^2小于lb时,再往左看也没有意义了。@Marko我的意思是分别对区间的每个边界进行二进制搜索。然后使用公式right_index-left_index+1计算区间内有多少个数字。知道了,谢谢。那么复杂性是n*logn?