Intersection of Two Arrays|| LEETCODE 349|| O(N) Space and O(N) time. EASY Solution.

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

very nice solution bhaiya I used two hashsets but I also liked ur code as well.

satyamgupta
Автор

// Q.6.1 Find the Intersection of the two sorted arrays.

// - time complexity N+M

// public class array_Question{
// public static void Intersection(int arr1[], int arr2[]){

// for (int i = 0; i < arr1.length; i++) {
// for (int j = 0; j < arr2.length; j++) {
// if(arr1[i]==arr2[j]){
// System.out.println(arr1[i]);
// }

// }

// }
// }
// public static void main(String[] args) {
// int arr1[]={1, 3, 2, 2, 4, 5, 7};
// int arr2[]={2, 3, 5, 6, 1};
// Intersection(arr1, arr2);

// }
// }

// Another Method

// - time complexity 0(N+M)

// import java.util.*;

// public class array_Question{
// public static void Intersection(int arr1[], int arr2[]){

// Arrays.sort(arr1);
// Arrays.sort(arr2);

// int i= 0;
// int j=0;

// while (i<arr1.length && j<arr2.length) {
// if(arr1[i]==arr2[j]){
// System.out.println(arr1[i]);
// i++;
// j++;
// }
// else if(arr1[i]>arr2[j]){
// j++ ;

// }
// else{
// i++;
// }

// }
// }
// public static void main(String[] args) {
// int arr1[]={1, 3, 2, 2, 4, 5, 7};
// int arr2[]={2, 3, 5, 6, 1};
// Intersection(arr1, arr2);

// }
// }
// Another Method

// import java.util.ArrayList;
// import java.util.HashSet;
// public class array_Question {
// public static void Intersection(int arr1[], int arr2[]) {
// HashSet<Integer> set1 = new HashSet<>();
// ArrayList<Integer> answer = new ArrayList<>();

// for (int i = 0; i < arr1.length; i++) {
// set1.add(arr1[i]);

// }
// for (int i = 0; i < arr2.length; i++) {
// if (set1.contains(arr2[i])) { // set1 element contains elements of any arr2 then i will put that element in my answer .
// answer.add(arr2[i]);
// set1.remove(arr2[i]) ; // to save from duplicates

// }
// }
// System.out.println(answer);
// }
// public static void main(String[] args) {
// int arr1[] = {1, 5, 3, 2, 2, 4, 5, 7};
// int arr2[] = {2, 3, 5, 6, 1, 5};
// Intersection(arr1, arr2);
// }
// }

techkid
Автор

C++ Solution:
unordered_set<int> s;
vector<int>ans;


for(int i=0 ; i<nums1.size(); i++){

s.insert(nums1[i]);
}

for(int i=0; i<nums2.size(); i++){

if(s.find(nums2[i]) != s.end()){
ans.push_back(nums2[i]);
s.erase(nums2[i]);
}
}
return ans;

gyandangi
Автор

Hello please muje bataiye ki mera code right hai ya nahi
#include <stdio.h>
int main()
{
int a1[] = {1, 2, 3, 4};
int a2[] = {2, 2, 2, 4};
int a3[50];
int count = 0, k = 0, i, j, size1, size2;
size1 = sizeof(a1) / sizeof(a1[0]);
size2 = sizeof(a2) / sizeof(a2[0]);

for (i = 0; i < size1; i++)
{
for (j = 0; j < size2; j++)
{
if (a1[i] == a2[j])
{
a3[k] = a2[j];
count++;
k++;
break;
}
}
}
for (k = 0; k < count; k++)
{
printf("%d\t", a3[k]);
}
}

prathampatel
Автор

for some reason my code isn't working

IshikaAgarwal