leeCode350_ intersection of two arrays

1. Subject content

Given two arrays, write a function to calculate their intersection.

Example 1: 输入:nums1 = [1,2,2,1], nums2 = [2,2] 输出:[2,2]
Example 2: 输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出:[4,9]
Description:

  1. The number of occurrences of each element in the output result should be consistent with the minimum number of occurrences of the element in the two arrays.
  2. We can ignore the order of output results.

Advanced:

  1. What if the given array is already sorted? How will you optimize your algorithm?
  2. If the size of nums1 is much smaller than nums2, which method is better?
  3. If the elements of nums2 are stored on the disk, the memory is limited, and you cannot load all the elements into the memory at once, what should you do?

Two, problem-solving ideas

First get this question, we basically can immediately think, this question can be seen as a traditional title maps (map maps), is
what it can look like this, because we need to find the intersection of two elements of the array, and should The same as the number of occurrences in the two arrays
. This leads to the need to know the number of times each value appears, so the mapping relationship becomes <element, number of occurrences>. The rest
is to solve the problem smoothly.

Three, code implementation

func intersect(nums1 []int, nums2 []int) []int {
    
     
	m0 := map[int]int{
    
    } 
	for _, v := range nums1 {
    
    
		//遍历nums1,初始化map 
		m0[v] += 1 
	}
	k := 0 
	for _, v := range nums2 {
    
     
	//如果元素相同,将其存入nums2中,并将出现次数减1 
		if m0[v] > 0 {
    
     
			m0[v] -=1 
			nums2[k] = v 
			k++ 
		} 
	}
	return nums2[0:k] 
}

Guess you like

Origin blog.csdn.net/qq_44880095/article/details/112933169