码迷,mamicode.com
首页 > 其他好文 > 详细

两个集合求对称差集

时间:2016-02-23 13:17:17      阅读:536      评论:0      收藏:0      [点我收藏+]

标签:

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

比如,集合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}));
    }

 

两个集合求对称差集

标签:

原文地址:http://www.cnblogs.com/23lalala/p/5209238.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!