[Algorithms and Data Structures] The intersection of two arrays of 349 and LeetCode

For all the LeetCode solution indexes, you can read this article - [Algorithm and Data Structure] LeetCode Solution .

1. Topic

insert image description here

Second, the solution

  Idea analysis: Use a hash array to record the numbers that appear in nums1, and then traverse nums2 to find the value of 1 in the hash array, which is the element of the intersection.
  The procedure is as follows

class Solution {
    
    
public:
	vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    
    
		unordered_set<int> result;
		int hashTable[1005] = {
    
     0 };	// 哈希数组
		for(int num : nums1) hashTable[num] = 1;	// nums1记录出现的数字
		for (int num : nums2) {
    
    
			if (hashTable[num]) {
    
    
				result.insert(num);
			}
		}
		return vector<int>(result.begin(), result.end());
	}
};

Complexity analysis:

  • time complexity: O ( m + n ) O(m+n) O(m+n ) , m and n are respectively divided into the lengths of the two arrays, and the program traverses the two arrays respectively.
  • Space complexity: O ( t ) O(t) O ( t ) , wheret = min ( m , n ) t = min(m, n)t=min(m,n ) , the largest intersection of two arrays may be the shorter array.

3. Complete code

# include <iostream>
# include <unordered_set>
# include <vector>
# include <string>
using namespace std;

class Solution {
    
    
public:
	vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    
    
		unordered_set<int> result;
		int hashTable[1005] = {
    
     0 };	// 哈希数组
		for(int num : nums1) hashTable[num] = 1;	// nums1记录出现的数字
		for (int num : nums2) {
    
    
			if (hashTable[num]) {
    
    
				result.insert(num);
			}
		}
		return vector<int>(result.begin(), result.end());
	}
};

void VectorGenerator(int arr[], int len, vector<int>& nums1) {
    
    
	for (int i = 0; i < len; i++) {
    
    
		nums1.push_back(arr[i]);
	}
}

void my_print(vector <int>& v, string msg)
{
    
    
	cout << msg << endl;
	for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
	{
    
    
		cout << *it << "  ";
	}
	cout << endl;
}

int main()
{
    
    
	int arr1[] = {
    
     4,9,5 };
	int arr2[] = {
    
     9,4,9,8,4 };
	int arr1_len = sizeof(arr1) / sizeof(int);
	int arr2_len = sizeof(arr2) / sizeof(int);
	vector<int> nums1, nums2;
	VectorGenerator(arr1, arr1_len, nums1);
	VectorGenerator(arr2, arr2_len, nums2);
	my_print(nums1, "nums1:");
	my_print(nums2, "nums2:");
	Solution s1;
  	vector<int> result = s1.intersection(nums1, nums2);
	my_print(result, "result:");
	system("pause");
	return 0;
}

end

Guess you like

Origin blog.csdn.net/qq_45765437/article/details/131224516