题解 | #农场牛类别匹配#
农场牛类别匹配
https://www.nowcoder.com/practice/270db1e1d65b4366a49a517ec7822912
题目考察的知识点是:
哈希的运用。
题目解答方法的文字分析:
在 countMatchingPairs 方法中定义一个整型变量 count,用于记录满足条件的配对数,初始值为 0。然后使用两层循环遍历数组 breeds:外层循环从索引 0 开始遍历到倒数第二个元素,内层循环从外层循环的下一个索引开始遍历到最后一个元素。对于每一对索引 i 和 j,我们通过判断 breeds[i] + breeds[j] 是否等于 target_sum 来确定是否找到了满足条件的配对。如果满足条件,则将计数器 count 加1。循环结束后,返回计数器 count 的值,即为满足条件的配对数。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
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;
}
}
#题解#
