美文网首页
793. Intersection of Arrays

793. Intersection of Arrays

作者: Anseis | 来源:发表于2018-04-06 13:51 被阅读0次

    Intersection of Arrays
    给出多个数组,求它们的交集。输出他们交集的大小。

    思路如下:
    首先用一个set把第一行数字存进去

    然后从第二行开始遍历,层级遍历,把每层和上一层一样的数字存进一个新的set里,然后更新set用于下一行查找,最后set里面的数字数目就是全部的交集。

    public class Solution {
        /**
         * @param arrs: the arrays
         * @return: the number of the intersection of the arrays
         */
        public int intersectionOfArrays(int[][] arrs) {
            // write your code here\
            Set<Integer> set = new HashSet<>();
            for(int i = 0; i < arrs[0].length; i++){
                set.add(arrs[0][i]);
            }
            for(int i = 1; i < arrs.length; i++){
                Set<Integer> set1 = new HashSet<>();
                for(int j = 0; j < arrs[i].length; j++){
                    if(set.contains(arrs[i][j])){
                        set1.add(arrs[i][j]);
                    }
                }
                set = set1;
            }
            return set.size();
        }
    }
    

    相关文章

      网友评论

          本文标题:793. Intersection of Arrays

          本文链接:https://www.haomeiwen.com/subject/avqshftx.html