玩命加载中 . . .

349/350-两个数组的交集


LeetCode 349. Intersection of Two Arrays

LeetCode-349

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

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]
Explanation: [4,9] is also accepted.

method: 哈希表

求两个数组的交集,重复的只算一个

哈希值置1和置0可以达到去重的目的,不管出现多少次,哈希值都是1

vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    unordered_map<int, int> hash;
    vector<int> ret;
    for (auto n : nums1) hash[n] = 1;
    for (auto n : nums2) {
        if (hash[n]) {
            ret.push_back(n);
            hash[n]--;
        }
    }
    return ret;
}

LeetCode 350. Intersection of Two Arrays II

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]

Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.

method

哈希表存储nums1中字符出现次数,nums2中的字符减少相应哈希值,如果减少之后哈希值还大于等于0,说明nums1中出现了相应字符

vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
    int hash[1001] = {0};
    for (auto n : nums1) {
        hash[n]++;
    }
    vector<int> res;
    for (auto n : nums2) {
        if (--hash[n] >= 0) res.push_back(n);
    }
    return res;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录