Find the intersection of two arrays. Each element in the result should appear as many times as it shows in both arrays.
Example:
Input: nums1[] ={1,2,2,1}, nums2[] = {2,2}
Output: inter[]={2,2}
Approach
Java
import java.util.ArrayList;import java.util.Arrays;public class IntersectionofTwoArraysII {public static void main(String[] args) {int nums1[] = { 4, 9, 5,9 };int nums2[] = { 9, 4, 9, 8, 4 };int intsec[] = intSecTwoArray(nums1, nums2);System.out.println(Arrays.toString(intsec));}private static int[] intSecTwoArray(int[] nums1, int[] nums2) {// first array lengthint fl1 = nums1.length;// second array lengthint sl2 = nums2.length;// define pointerint f = 0, s = 0;ArrayList<Integer> set = new ArrayList<>();// sort the both arrayArrays.sort(nums1);Arrays.sort(nums2);// two-pointer approachwhile (fl1 > f && sl2 > s) {// if both equalsif (nums1[f] == nums2[s]) {set.add(nums1[f]);f++;s++;} else if (nums1[f] > nums2[s]) {s++;} else if (nums1[f] < nums2[s]) {f++;}}// set to arrayint result[] = set.stream().mapToInt(Number::intValue).toArray();return result;}}
C++
#include <bits/stdc++.h>using namespace std;//function to find the intersection of//two arraysvector<int> intersect(vector<int>& nums1, vector<int>& nums2){int n=nums1.size();int m=nums2.size();//sort both the arrayssort(nums1.begin(),nums1.end());sort(nums2.begin(),nums2.end());int i=0,j=0;vector<int> res;//ietare till the end of the arrayswhile(i<n && j<m){//if both are sam then//push into the resultif(nums1[i]==nums2[j]){res.push_back(nums1[i]);i++;j++;}//if fisrt is smaller then move first//to next positionelse if(nums1[i]<nums2[j])i++;//else move second to the next positionelse if(nums1[i]>nums2[j])j++;}return res;}int main(){vector<int> nums1={1,2,2,1};vector<int> nums2={2,2};vector<int> inter=intersect(nums1,nums2);for(int i=0;i<inter.size();i++)cout<<inter[i]<<" ";}
No comments:
Post a Comment