134.Intersection of Two Arrays II

来源:互联网 发布:海纳百川软件下载 编辑:程序博客网 时间:2024/05/22 14:43

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 num2'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?

Subscribe to see which companies asked this question

与133类似 ,只不过是这个题目选择的容器是list

public int[] intersect(int[] nums1, int[] nums2) {/*Step1:初始化及临界值操作*/int len1 = nums1.length;int len2 = nums2.length;int result[];ArrayList<Integer> re = new ArrayList<Integer>();if(len1 * len2 <=0){result = new int[0];return result;}/*Step2:把nums1数组放到LinkedList中*/LinkedList list = new LinkedList();for(int i=0;i<len1;i++){list.add(nums1[i]);}/*Step3:遍历nums2,如果在LinkedList中则拿出这个元素*/for(int i=0;i<len2;i++){if(list.contains(nums2[i])){re.add(nums2[i]);list.remove((Integer)nums2[i]);}}/*Step4:整理返回的结果*/int len = re.size();result = new int[len];for(int i=0;i<len;i++){result[i] = re.get(i);}        return result;    }


0 0