给定两个给定的相等长度的数组A和B ,任务是找到可以选择的最大对不同元素对,以使A中的元素严格大于B中的元素。
例子:
Input:
A[]={20, 30, 50} , B[]={25, 60, 40}
Output: 2
Explanation:
(30, 25) and (50, 40) are the two possible pairs.
Input:
A[]={20, 25, 60} , B[]={25, 60, 40}
Output: 1
Explanation:
(60, 25) or (60, 40) can be the required pair.
方法:为了解决此问题,我们需要采用以下方法:
- 对两个数组进行排序。
- 遍历数组A的整个长度,并检查A中的当前元素是否大于B中当前指向B的元素。
- 如果是这样,则指向两个数组中的下一个元素。否则,移至A中的下一个元素,并检查它是否大于当前指向B的元素。
- 在数组A的整个遍历之后,在数组B中遍历的元素数量给出了所需的答案。
Illustration:
Let us consider the two following arrays:
A[] = { 30, 28, 45, 22 } , B[] = { 35, 25, 22, 48 }
After sorting, the arrays appear to be
A[] = { 22, 28, 30, 45 } , B[] = { 22, 25, 35, 48}
After the first iteration, since A[0] is not greater than B[0], we move to A[1].
After the second iteration, we move to B[1] as A[1] is greater than B[0].
After the third iteration, we move to B[2] as A[2] is greater than B[1].
Similarly, A[3] is greater than B[2] and we move to B[3].
Hence the number of elements traversed in B,i.e. 3 is the final answer.
The possible pairs are (28,22), (30,25) are (45, 35).
下面是上述方法的实现: