Daily Question: Intersection of Two Arrays||

Get into the habit of writing together! This is the 8th day of my participation in the "Nuggets Daily New Plan·April Update Challenge", click to view the details of the event 

topic link

nums1 Given the sum  of two integer arrays  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 the same as the number of times the element appears in both arrays ( if the number of occurrences is inconsistent, the smaller value is considered ). The order of 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]
复制代码

  hint:

  • 1 <= nums1.length, nums2.length <= 1000
  • 0 <= nums1[i], nums2[i] <= 1000

Problem-solving ideas: (Hash table)

This question is similar to a question I wrote before. If you are interested, you can do that question first, then do this question, the intersection of two arrays|

Because this question does not require the elements in the array to be non-repetitive, which means that an element may appear multiple times in the array, we need to use a hash table to record the number of times the element appears in the array . The number of occurrences of an element should be the minimum of its occurrences in the two arrays

And because the length of the intersection of the two arrays must not exceed the length of the shorter array , we first traverse the shorter array and record the number of occurrences of each element and element in the hash table

Specific ideas:

  1. First compare the lengths of the two arrays to find the shorter arraynums1
  2. Traverse nums1and record the value and number of occurrences of each element in the hash table
  3. Create a new array and return it as the result, the length of the array is nums1the length of
  4. Then traverse another array nums2, for nums2each element in the hash table, if it can be found in the hash table, add the element to the result array, and reduce the number of occurrences of this element in the hash table

Code: (JAVA implementation)

public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2,nums1);
        }
        HashMap<Integer,Integer> hashmap = new HashMap<>();
        for (int i : nums1) {
            //这里的count就是每个元素出现的次数,后面的+1是为了保证添加进哈希表的元素至少有一次
            int count = hashmap.getOrDefault(i,0)+1;
            hashmap.put(i,count);
        }

        int[] nums = new int[nums1.length];
        //记录结果数组元素的个数
        int index = 0;
        for (int i : nums2) {
            int count = hashmap.getOrDefault(i,0);
            if (count > 0) {
                nums[index] = i;
                index++;
                count--;
                if (count > 0) {
                    hashmap.put(i,count);
                }else {
                    hashmap.remove(i);
                }
            }
        }
       
        return Arrays.copyOfRange(nums,0,index);
复制代码

Complexity Analysis

  • Time complexity: O(M+N) , where  m and  n are the lengths of the two arrays respectively. Need to traverse two arrays and operate on the hash table, the time complexity of the hash table operation is  O(1), so the total time complexity is linear with the sum of the lengths of the two arrays.
  • Space complexity: O(min(M,N)) , where  m and  n are the lengths of the two arrays respectively. Hash table operations are performed on shorter arrays, and the size of the hash table will not exceed the length of the shorter array. Creates an array for the return value  numswhose length is the length of the shorter array.

Submit results

image.png

Problem-solving ideas: (sort + double pointer)

If the two arrays are sorted , we can traverse the two pointers to get the intersection of the arrays

Specific ideas:

  1. Sort the two arrays first, then traverse with double pointers
  2. At the beginning, the two pointers point to the beginning of the two arrays, respectively, and compare whether the elements pointed to by the pointers are equal. If the two pointers are equal, the elements are added to the result array, and the arrays are moved one bit backward at the same time. If they are not equal, the elements are compared. The small pointer is moved back one bit, and when at least one pointer exceeds the range of the array, the traversal ends

Code: (JAVA implementation)

public static int[] intersect(int[] nums1,int[] nums2) {
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    int l1 = nums1.length;
    int l2 = nums2.length;

    int[] ints = new int[Math.min(l1,l2)];

    int nums1_index = 0;
    int nums2_index = 0;
    int ints_index = 0;

    while (nums1_index < l1 && nums2_index < l2) {
        if (nums1[nums1_index] < nums2[nums2_index]) {
            nums1_index++;
        }else if (nums1[nums1_index] > nums2[nums2_index]) {
            nums2_index++;
        }else {
            ints[ints_index++] = nums2[nums2_index];
            nums1_index++;
            nums2_index++;
        }
    }

    return Arrays.copyOfRange(ints,0,ints_index);
}
复制代码

Complexity Analysis:

  • Time complexity: O(mlogm+nlogn)
  • Space complexity: O(min(m,n)) , where  m and  n are the lengths of the two arrays respectively. Creates an array for the return value  intswhose length is the length of the shorter array

Submit results

image.png

Guess you like

Origin juejin.im/post/7084920623515828254