Leetcode349. Intersection of Two Arrays

题目描述:

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

Example:

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

题目要求:

题目要求我们返回两个数组的交集,需要注意的是结果集的元素必须是有序并且唯一的。

解题思路:
- 可以使用首先将一个数组存入HashSet中,然后将第二个数组中的元素分别依次比较,看是否在HashSet中,如果存在则添加到需要返回的结果数组中。

最终实现:

public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            if (nums1 == null || nums2 == null) {
                return null;
            }
            Set set1 = new HashSet<>();
            for (int i:nums1) {
                set1.add(i);
            }

            Set set2 = new HashSet<>();
            for (int i:nums2) {
                if (set1.contains(i)) {
                    set2.add(i);
                }
            }

            int[] result = new int[set2.size()];
            int i = 0;
            for (int n:set2) {
                result[i++] = n;
            }
            return result;
        }
    }

这种方法时间复杂度为O(n),空间复杂度为O(n)。

另外的解:

  • 另外一种解题思路是,首先对数组进行排列,然后借助Arrays中的binarySearch方法,对每个元素进行二分查找,具体实现如下:
public class Solution {
        public static int[] intersection(int[] num1, int[] num2) {
            Arrays.sort(num1);
            Arrays.sort(num2);

            ArrayList aList = new ArrayList<>();
            for (int i = 0; i < num1.length; i++) {
                if (i == 0 || (i > 0 && num1[i] != num1[i-1])) {
                    if (Arrays.binarySearch(num2, num1[i]) > -1) {
                        aList.add(num1[i]);
                    }
                }
            }
            int[] result = new int[aList.size()];
            int k = 0;
            for (int i : aList) {
                result[k++] = i;
            }
            return result;
        }
    }

对于上面的binarySearch方法,即可以自己实现也可以调用Arrays类中的静态方法,在这里就不实现了。

你可能感兴趣的:(LeetCode)