Intersection of Two Arrays (两数组的交 )

问题

Given two arrays, write a function to compute their intersection.
** Notice
Each element in the result must be unique.
The result can be in any order.

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

方法1

分析

因为要求结果的元素不重复,所以考虑使用Set.
把一个数组用转化为Set存储去重,遍历另外一个数组。有相同的就存起来,并且把它从Set中移除,避免后边添加两次。最后把结果转化为数组返回。

代码
public class Solution {
    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // Write your code here
        Set set=new HashSet();
        for(int i:nums1){
            set.add(i);
        }
        ArrayList list=new ArrayList();
        for(int i:nums2){ 
            if(set.contains(i)){
                list.add(i);
                set.remove(i);
            }
        }
        int[] res=new int[list.size()];
        for(int i=0;i

方法2

分析

将两个数组都进行排序,然后使用归并排序的思路,同时进行遍历,小的指针++,相同就放入set中,指针同时++,当有一个遍历完时结束。
最后把结果转化为数组返回。

代码

    /**
     * @param nums1 an integer array
     * @param nums2 an integer array
     * @return an integer array
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        // Write your code here
        List list=new ArrayList();
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int index1=0;
        int index2=0;
        while(true){
            if(index1>=nums1.length||index2>=nums2.length){
                break;
            }
            int a=nums1[index1];
            int b=nums2[index2];
            if(a==b){
                index1++;
                index2++;
                if(!list.contains(a)){
                    list.add(a);
                }
            }else if(a>b){
                index2++;
            }else if(a

你可能感兴趣的:(Intersection of Two Arrays (两数组的交 ))