题解 | #农场牛类别匹配#

农场牛类别匹配

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;
    }
}

全部评论

相关推荐

10-02 19:29
已编辑
浙江科技大学 运营
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务