349. Intersection of Two Arrays & 350. Intersection of Two Arrays II

来源:互联网 发布:linux 启动过程 编辑:程序博客网 时间:2024/05/16 19:55
349
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.

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        //判断待比较数组如果为空,则返回null        if(nums1==null||nums2==null)            return null;       //将nums1存入HashSet,避免了重复元素的产生,构建一个新的arraylist       Set<Integer> num =new HashSet<Integer>();       for(int i=0;i<nums1.length;i++)       {           num.add(nums1[i]);       }       List<Integer> a = new ArrayList<Integer>();       //遍历数组nums2,如果set中有此元素,存入一个arraylist,并且删除set中对应的元素       for(int i=0;i<nums2.length;i++)       {           if(num.contains(nums2[i]))           {               a.add(nums2[i]);               num.remove(nums2[i]);//防止add重复的数据           }       }       //遍历list转变为array返回       int[] res=new int[a.size()];       for(int i=0;i<a.size();i++)       {           res[i]=(int)a.get(i);       }       return res;    }}

350

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

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

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

  • What if the given array is already sorted? How would you optimize your algorithm?
  • What if nums1's size is small compared to nums2's size? Which algorithm is better?
  • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

public class Solution {    public int[] intersect(int[] nums1, int[] nums2) {        //判断待比较数组如果为空,则返回null        if(nums1==null||nums2==null)            return null;      //用Arrays.sort将两个nums排序,底层使用快排      Arrays.sort(nums1);      Arrays.sort(nums2);      //用两个for循环遍历比较nums1和nums2,如果等于,把对应的元素add到list中;如果nums1大于nums2,nums2后移一位;如果nums1小于nums2,nums1后移一位       List<Integer> a = new ArrayList<Integer>();       int i=0,j=0;       while(i<nums1.length&&j<nums2.length)       {           if(nums1[i]==nums2[j])           {               a.add(nums1[i]);               i++;               j++;           }           else if(nums1[i]>nums2[j])           {               j++;           }           else           {               i++;           }       }       //遍历list转变为array返回       int[] res=new int[a.size()];       for(int k=0;k<a.size();k++)       {           res[k]=(int)a.get(k);       }       return res;    }}



0 0
原创粉丝点击