import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param breeds int整型一维数组 * @param target_sum int整型 * @return int整型 */ public int countMatchingPairs (int[] breeds, int target_sum) { // write code here int count = 0; for (int i = 0; i < breeds.length; i++) { for (int j = i + 1; j < breeds.length; j++) { if ((breeds[i] + breeds[j]) == target_sum) { count++; } } } return count; } }
编程语言是Java。
这道题目考察的是双重循环和条件判断。
具体代码的文字解释如下:
- 在
countMatchingPairs
方法中定义一个整型变量count
,用于记录满足条件的配对数,初始值为 0。 - 然后使用两层循环遍历数组
breeds
:外层循环从索引 0 开始遍历到倒数第二个元素,内层循环从外层循环的下一个索引开始遍历到最后一个元素。 - 对于每一对索引 i 和 j,我们通过判断
breeds[i] + breeds[j]
是否等于target_sum
来确定是否找到了满足条件的配对。如果满足条件,则将计数器count
加1。 - 循环结束后,返回计数器
count
的值,即为满足条件的配对数。