头图

title: Daily practice (46): intersection of two arrays

categories:[Swords offer]

tags:[Daily practice]

date: 2022/04/21


Daily practice (46): intersection of two arrays

Given an array nums containing n numbers in [0, n], find the number in the range [0, n] that does not appear in the array.

Example 1:

Input: nums = [3,0,1]

output: 2

Explanation: n = 3, since there are 3 numbers, all numbers are in the range [0,3]. 2 is the missing number because it doesn't appear in nums.

Example 2:

Input: nums = [0,1]

output: 2

Explanation: n = 2, since there are 2 numbers, all numbers are in the range [0,2]. 2 is the missing number because it doesn't appear in nums.

Example 3:

Input: nums = [9,6,4,2,3,5,7,0,1]

output: 8

Explanation: n = 9, since there are 9 numbers, all numbers are in the range [0,9]. 8 is the missing number because it doesn't appear in nums.

Example 4:

Input: nums = [0]

output: 1

Explanation: n = 1, since there is 1 number, all numbers are in the range [0,1]. 1 is the missing number because it doesn't appear in nums.

hint:

n == nums.length

1 <= n <= 104

0 <= nums[i] <= n

All numbers in nums are unique

Source: LeetCode

Link: https://leetcode-cn.com/problems/missing-number

Method 1: Simple Hash

Thought analysis

Traverse nums1 and record it with cnt, cnt[i] indicates how many times the number i appears in nums.

Traverse nums2 to determine whether cnt[i] is greater than 0. The greater than indicates that there is this number in nums1, remember to set cnt[i] = 0, otherwise add the same number repeatedly.

 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    int cnt[1001]{0};
    vector<int> res;
    for (auto i : nums1) {
        cnt[i]++;
    }
    for (auto i : nums2) {
        if (cnt[i] > 0) {
            res.push_back(i);
            cnt[i] = 0;
        }
    }
    return res;
}

Method 2: Set method

Thought analysis

First define a set container to copy nums1 into it and then traverse the nums2 array to see if there is an element in nums2 in the map container, if it exists, save the value

 vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    unordered_set<int> result;
    unordered_set<int> nums1_set(nums1.begin(), nums1.end());/* 由于输出的元素唯一不重复因此可以将nums1转化为unordered_set哈希表 */
    for (int i = 0; i < nums2.size(); i++) {
        if (nums1_set.find(nums2[i]) != nums1_set.end()) { /* 判断nums1_set中是否有nums2的元素,若有将此值插入到result */
            result.insert(nums2[i]);
        }
    }
    return vector<int> (result.begin(), result.end());
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记