原题网址:https://leetcode.com/problems/intersection-of-two-arrays/
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
- Each element in the result must be unique.
- The result can be in any order.
方法:通过集合求交集。
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for(int num: nums1) set1.add(num);
for(int num: nums2) if (set1.contains(num)) set2.add(num);
int[] result = new int[set2.size()];
int i=0;
for(int num: set2) result[i++] = num;
return result;
}
}

本文介绍了一种利用集合操作解决LeetCode上两数组交集问题的方法。通过将两个数组转换为集合,并利用集合的交集特性来找出共同元素。
706

被折叠的 条评论
为什么被折叠?



