题解 | #农场牛类别匹配#
农场牛类别匹配
https://www.nowcoder.com/practice/270db1e1d65b4366a49a517ec7822912
第一种双循环暴力算法
第二种使用hash碰撞。
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param breeds int整型一维数组
* @param target_sum int整型
* @return int整型
*/
public int countMatchingPairs (int[] breeds, int target_sum) {
int sum = 0;
// write code here
Map<Integer, Integer> breedMap = new HashMap<>();
for(int i = 0; i < breeds.length; i++) {
if (breedMap.containsKey(target_sum - breeds[i])) {
sum ++;
breedMap.remove(target_sum - breeds[i]);
} else {
breedMap.put(breeds[i], -1);
}
}
return sum;
}
}
查看21道真题和解析
小天才公司福利 1159人发布