349.Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output: [9,4]
Note:
- Each element in the result must be unique.
- The result can be in any order.
思路:给定两个数组,编写一个函数来计算它们的交集。
使用Set集合不会存储重复元素的特性。先遍历其中一个数组存入Set集合,再遍历另一个数组在Set中查找是否存在,若存在添加到一个新的Set集合中。
代码如下:
public class IntersectionOfTwoArrays { private static int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); for (int i2 : nums1) { set1.add(i2); } Set<Integer> set2 = new HashSet<>(); for (int i1 : nums2) { if (set1.contains(i1)) { set2.add(i1); } } int[] result = new int[set2.size()]; int i = 0; for (int cell : set2) { result[i++] = cell; } return result; } public static void main(String[] args) { int[] nums1 = {4, 9, 5}; int[] nums2 = {9, 4, 9, 8, 4}; int[] res = IntersectionOfTwoArrays.intersection(nums1, nums2); for (int i : res) { System.out.println(i); } } }