数组配对

问题: 给定N个整数,N为偶数,是否能找到N/2对,使得每对和能被K整除。注意:每个元素只能出现在一个配对中。

思路: 创建一个长度为K的数组,将整数的个数按照余数分类存储到数组中,分析余数情况。

boolean checkPairable(int[] nums,int k){
        if(k<0)
            return false;
        int[] counts=new int[k];
        for(int num:nums){
            counts[num%k]++;
        }
        if(counts[0]%2!=0)
            return false;
        if(k%2==0){
            if(counts[k/2]%2!=0)
                return false;
        }
        for(int i=1;i<k/2;i++)
        {
            if(counts[i]!=counts[k-i])
                return false;
        }
        return true;
    }
发布了18 篇原创文章 · 获赞 0 · 访问量 671

猜你喜欢

转载自blog.csdn.net/qq_42060170/article/details/104253763