Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
找两个数组中的交集,每个交集元素值只保留一次。用hash set存下一个数组的所有元素然后遍历另一个数组当遇到在set里的就插入到结果,并为了去重再在set中删去对应元素。
/*
* @lc app=leetcode id=349 lang=cpp
*
* [349] Intersection of Two Arrays
*/
// @lc code=start
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> s(nums1.begin(), nums1.end());
vector<int> res;
for (const auto num : nums2) {
if (s.count(num)) {
res.push_back(num);
s.erase(num);
}
}
return res;
}
};
// @lc code=end
假设已经排好序. 两个指针指向两个数组的头, 依次往前走就好.
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
Set<Integer> set = new HashSet<>();
for (int i = 0, j = 0; i < nums1.length && j < nums2.length;) {
if (nums1[i] < nums2[j]) {
i++;
} else if (nums1[i] > nums2[j]) {
j++;
} else {
set.add(nums1[i]);
i++;
j++;
}
}
int[] result = new int[set.size()];
int k = 0;
for (Integer num : set) {
result[k++] = num;
}
return result;
}
}
不算排序的话时间复杂度O(N).