Intersection Leetcode349. Two arrays

Title Description

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Description:

The output of each element must be unique. We can not consider the order of output.

answer

Set to the weight method (java)

Thinking: two arrays respectively set in the array, thereby completing the work of de-emphasis, and then use the built-in function set.retainAll()may be removed and set in the input set of duplicate parts.

retainAll function Portal

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> set2 = new HashSet<>();
        for (int num1 : nums1) set1.add(num1);
        for (int num2 : nums2) set2.add(num2);
        set1.retainAll(set2);
        int[] ans = new int[set1.size()];
        int index = 0;
        
        for(int num : set1) ans[index++] = num;
        return ans;
    }
}

Complexity Analysis

  • time complexity: THE ( N + M ) O(N + M)
  • Space complexity: THE ( N + M ) O(N + M)

Method to weight set 2 (java)

Thinking: Thinking and also similar to the above, the wording: when there is a set of the parent element in the subset is not added, the final output value of the direct subset. Faster than the above wording a little.

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
            return new int[0];
        }
        Set<Integer> parentSet = new HashSet<>();
        Set<Integer> childSet = new HashSet<>();
        for (int num : nums1) {
            parentSet.add(num);
        }
        for (int num : nums2) {
            if (parentSet.contains(num)) {
                childSet.add(num);
            }
        }
        int[] resArr = new int[childSet.size()];
        int index = 0;
        for (int value : childSet) {
            resArr[index++] = value;
        }
        return resArr;
    }
}

Complexity Analysis

  • time complexity: THE ( N + M ) O(N + M)
  • Space complexity: THE ( N + M ) O(N + M)
Published 43 original articles · won praise 20 · views 1446

Guess you like

Origin blog.csdn.net/Chen_2018k/article/details/104912132