Lintcode Array (ii)

Source: Internet
Author: User

two the intersection of the array

two the intersection of the array

Example: Nums1 = [1, 2, 2, 1] , Nums2 = [2, 2] , return [2] .

Solution one: With two hashset

 Public int[] Intersection (int[] nums1,int[] nums2) {Set<Integer> set =NewHashset<integer>(); Set<Integer> inter =NewHashset<>();  for(inti=0; i<nums1.length; i++) {Set.add (nums1[i]); }     for(intj=0; j<nums2.length; J + +){        if(Set.contains (Nums2[j])) {Inter.add (nums2[j]); }    }    int[] rst =New int[Inter.size ()]; intK = 0;  for(Integer s:inter) {rst[k++] =s; }    returnrst;}

Answer two: Sort two arrays, and then iterate through them with one pointer.

 Public int[] Intersection (int[] nums1,int[] nums2) {Set<Integer> set =NewHashset<integer>();    Arrays.sort (NUMS1);    Arrays.sort (NUMS2); intI=0, j=0;  while(I<nums1.length && j<nums2.length) {        if(nums1[i]<Nums2[j]) {i++; }Else if(nums1[i]>Nums2[j]) {J++; }Else{set.add (nums1[i]); I++; J++; }    }    int[] arr =New int[Set.size ()]; intK = 0;  for(Integer s:set) {arr[k++] =s; }    returnarr;}

Solution Three: Sort the num2, then traverse the number in the NUM1, make a binary search in num2, find it and put it in the set.

Lintcode Array (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.