两个集合求对称差集

对称差集,两个集合的并集,减去交集。

比如,集合1,2,3和集合3,3,4,5的对称差是集合1,2,4,5。

想到的解法,将两个排序,两个集合分别用两个工作指针i,j。比较两个指针指向的元素,相同就都后移,不相同,更小的指针后移。

以下代码,给出了求对称差集数量的代码。

 

public static int distinctElementCount(int arr1[], int arr2[])
    {
        if (arr1.length == 0) {
            return arr2.length;
        }
        if (arr2.length == 0) {
            return arr1.length;
        }
        int count = 0;
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        int i=0,j=0, same = -1;
        while (i< arr1.length && j<arr2.length) {
            if (arr1[i] == arr2[j]) {
                same = arr1[i];
                i++;j++;
            } else if (arr1[i] == same) {
                i++;
            } else if (arr2[j] == same) {
                j++;
            } else if (arr1[i] < arr2[j]) {
                i++;
                count++;
            } else {
                j++;
                count++;
            }
        }
        count += arr1.length + arr2.length - i - j;

        return count;
    }

    @Test
    public void testDistinct() {
        Assert.assertEquals(6, distinctElementCount(new int[]{1,2,3,4}, new int[]{4,5,6,7}));
        Assert.assertEquals(7, distinctElementCount(new int[]{4,3,5,6}, new int[]{3,2,1,6,3,9,8,13}));
        Assert.assertEquals(12, distinctElementCount(new int[]{1,2,3,4,5,6,7,8,9,10}, new int[]{11,12,13,4,5,6,7,18,19,20}));
    }

 

转载于:https://www.cnblogs.com/23lalala/p/5209238.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值