Find the intersection of two arrays.
Example:
Input: nums1[] ={1,2,2,1}, nums2[] = {2,2}
Output: 2
Approach
Java
import java.util.Arrays;import java.util.HashSet;public class IntersectionofTwoArrays {public static void main(String[] args) {int nums1[] = { 4, 9, 5 };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;HashSet<Integer> set = new HashSet<>();// 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> intersection(vector<int>& nums1, vector<int>& nums2){//vector to hold the final resultvector<int> res;int n=nums1.size();int m=nums2.size();//sort both the arayssort(nums1.begin(),nums1.end());sort(nums2.begin(),nums2.end());int i=0,j=0;set<int> st;//now iterate for all all elementswhile(i<n && j<m){//if both are same then push into the setif(nums1[i]==nums2[j]){st.insert(nums1[i]);i++;j++;}//else if nums[i]<nums[j] then move//first to the next positionelse if(nums1[i]<nums2[j])i++;//else move second to next pointelse if(nums1[i]>nums2[j])j++;}for(auto it=st.begin();it!=st.end();it++)res.push_back(*it);sort(res.begin(),res.end());return res;}int main(){vector<int> nums1={1,2,2,1};vector<int> nums2={2,2};vector<int> inter=intersection(nums1,nums2);for(int i=0;i<inter.size();i++)cout<<inter[i]<<" ";}
No comments:
Post a Comment