https://www.lintcode.com/problem/set-operation/description
给定两个数组 A A A和 B B B,数组无重复元素。求其并集、交集和差集的大小。按数组的形式返回。
先求交集的大小,然后根据公式算即可。代码如下:
import java.util.HashSet; import java.util.Set; 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> set = new HashSet<>(); for (int i = 0; i < A.length; i++) { set.add(A[i]); } int common = 0; for (int i = 0; i < B.length; i++) { if (set.contains(B[i])) { common++; } } return new int[]{A.length + B.length - common, common, A.length - common}; } }时间复杂度 O ( l A + l B ) O(l_A+l_B) O(lA+lB),空间 O ( l A ) O(l_A) O(lA)。
