Leetcode 350 Intersection of Two Arrays II

Leetcode 350 Intersection of Two Arrays II

Title description:

Given you two integer arrays nums1 and nums2, please return the intersection of the two arrays as an array. The number of occurrences of each element in the returned result should be consistent with the number of occurrences of the element in both arrays (if the number of occurrences is inconsistent, consider taking a smaller value). The order of the output results can be ignored.

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]
Solution: sorting + double pointer
code:
class Solution {

public:

  vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {

​    sort(nums1.begin(),nums1.end());

​    sort(nums2.begin(),nums2.end());

​    int length1=nums1.size();

​    int length2=nums2.size();

​    vector<int> intersection;

​    int index1=0,index2=0;

​    while(index1<length1&&index2<length2)

​    {

​      if(nums1[index1]<nums2[index2])

​      {

​        index1++;

​      }

​      else if(nums1[index1]>nums2[index2])

​      {

​        index2++;

​      }

​      else

​      {

​        intersection.push_back(nums1[index1]);

​        index1++;

​        index2++;

​      }



​    }

​    return intersection;

  }

};


Problem-solving ideas:

First, sort the two arrays, then use two pointers index1, index to traverse the two arrays.

Initially, the two pointers point to the heads of the two arrays respectively, and each time the numbers of the two arrays pointed to by the two pointers are compared, if the two numbers are not equal, the pointer pointing to the smaller number is moved to the right by one bit, when the two When the numbers pointed to by two pointers are equal, add that number to the answer and move both pointers to the right by one bit. When at least one of the pointers is out of the range of the array, the traversal ends.

Guess you like

Origin blog.csdn.net/Duba_zhou/article/details/124785788