leetcode349. Intersection of Two Arrays

来源:互联网 发布:汽车销售软件有哪些 编辑:程序博客网 时间:2024/06/05 02:53

349. 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存储相同的元素,然后遍历set,存到数组中。

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        if (nums1 == null || nums1.length == 0) {            return nums1;        }        if (nums2 == null || nums2.length == 0) {            return nums2;        }        Set<Integer> set = new HashSet<Integer>();        Arrays.sort(nums1);        Arrays.sort(nums2);        int i = 0, j = 0;        while (i < nums1.length && j < nums2.length) {            if (nums1[i] < nums2[j]) {                i++;            } else if (nums1[i] == nums2[j]) {                set.add(nums1[i]);                i++;                j++;            } else {                j++;            }        }        int size = set.size();        int[] ret = new int[size];        int k = 0;        for (int num : set) {            ret[k++] = num;        }        return ret;    }}

这里写图片描述

解法二

用两个hashset,第一个hashset存储第一个数组中的不重复元素,第二个hashset存储两个数组的重复元素。遍历hashset用的iterator方法。

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        if (nums1 == null || nums1.length == 0) {            return nums1;        }        if (nums2 == null || nums2.length == 0) {            return nums2;        }        Set<Integer> set1 = new HashSet<Integer>();        Set<Integer> set2 = new HashSet<Integer>();        for (int i = 0; i < nums1.length; i++) {            set1.add(nums1[i]);        }        for (int j = 0; j < nums2.length; j++) {            if (set1.contains(nums2[j])) {                set2.add(nums2[j]);            }        }        int size = set2.size();        int[] ret = new int[size];        int k = 0;        Iterator<Integer> it = set2.iterator();        while (it.hasNext()) {            ret[k++] = it.next();        }        return ret;    }}

这里写图片描述

1 0
原创粉丝点击