Intersection of Arrays II

Source: Internet
Author: User

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

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

Note:

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

The code is as follows:

1  Public classSolution {2      Public int[] Intersect (int[] nums1,int[] nums2) {3List<integer> list=NewArraylist<>();4         5 Arrays.sort (NUMS1);6 Arrays.sort (NUMS2);7     8              for(inti=0,j=0;i<nums1.length&&j<nums2.length;)9             {Ten                 if(nums1[i]==Nums2[j]) One                 { A List.add (Nums1[i]); -i++; -J + +; the                 } -                 Else if(nums1[i]<Nums2[j]) -i++; -                 Else if(nums1[i]>Nums2[j]) +J + +; -             } +         int[] result=New int[List.size ()]; A          for(intI=0;i<list.size (); i++) atresult[i]=List.get (i); -          -         returnresult; -          -     } -}

Intersection of Arrays II

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.