1471. 集合运算

Description

Given two sets A, B, output the size of the union, intersection, and difference of A and B

  • The size of set does not exceed 1e6
  • The value in the set does not exceed 1e6
    Have you met this question in a real interview?

Example

Given A = [1,3,4,6], B = [1,5,10],return [6,1,3].

Explanation:
The union, intersection and difference of A and B are: [1,3,4,5,6,10], [1], [3,4,6]
The corresponding set size is: 6, 1, 3

Given A = [1,2,3], B = [4,5,6],return [6,0,3].

Explanation:
The union, intersection and difference of A and B are: [1,2,3,4,5,6]、[]、[1,2,3]
The corresponding set size is: 6, 0, 3

最快

public class Solution {
    /**
     * @param A: The set A
     * @param B: The set B
     * @return: Return the size of three sets
     */
    public int[] getAnswer(int[] A, int[] B) {
        // Write your code here
    
        Set<Integer> arrA = new HashSet<>();
        
        for(int a : A){
            arrA.add(a);
        }
        
        int num = 0;
        for(int a : B){
            if(arrA.contains(a)){
                num++;
            }
            
        }
        int allSet= A.length + B.length - num;
        int diffSet = A.length - num;
        int[] res = new int[]{allSet,num,diffSet};
        return res;
    }
}
public class Solution {
    /**
     * @param A: The set A
     * @param B: The set B
     * @return: Return the size of three sets
     */
    public int[] getAnswer(int[] A, int[] B) {
        // Write your code here
        int num = 0;
        int lenA = A.length;
        int lenB = B.length;
        
        for(int i=0; i<A.length;i++){
            for(int j=0; j<B.length;j++){
                if(A[i] == B[j]){
                    num++;
                }
   
            }
        }
        
        int allSet = lenA + lenB - num;
        int diffSet = lenA - num;
        int[] res = {allSet,num,diffSet};
        return res;
    }
}

描述
给定两个集合A,B,分别输出A和B的并集、交集和差集的大小

集合的大小不超过1e6
集合中出现的数值大小不超过1e6
您在真实的面试中是否遇到过这个题?  
样例
给出 A = [1,3,4,6], B = [1,5,10],返回 [6,1,3]。

解释:
A,B的并集、交集和差集分别为:[1,3,4,5,6,10]、[1]、[3,4,6]
对应的集合大小为:6、1、3
给出 A = [1,2,3], B = [4,5,6],返回 [6,0,3]。

解释:
A,B的并集、交集和差集分别为:[1,2,3,4,5,6]、[]、[1,2,3]
对应的集合大小为:6、0、3
posted @ 2019-04-02 21:49  故人叹  阅读(211)  评论(0)    收藏  举报