java
python
a =[2,3,5,6,3,4]
b=[3,5,1,6,0,7]
c=[]
for i in a:
if i in b:
if i in c:
pass
else:
c.append(i)
print(c)
C#
#include <stdio.h>
#include <stdlib.h>
#define M 5
#define N 7
void intersection(int array1[], int array2[])
{
int i = 0, j = 0;
while (i<M&&j<N)
{
//數組1第一個數和數組2第一個數比較,若小於,再用第二個數和數組2的第一個比較...
while (array1[i]<array2[j])
i++;
while (array1[i]>array2[j])
j++;
while (array1[i] == array2[j])
{
printf("%d ", array1[i]);
//兩個數組最後一個數字相同時 a[M-1] == a[N-1] == -858993460(vs2013環境下)
if (i == M - 1 && j == N - 1)
{
return;
}
else
{
i++;
j++;
}
}
}
}
int main()
{
int array1[M] = { 1, 3, 4, 7, 11 };
int array2[N] = { 2, 3, 5, 6, 7, 8, 11 };
intersection(array1, array2);
system("pause");
return 0;
}
c++
#include
#include
using namespace std;
int main ()
{
std::ios::sync_with_stdio (false);
setiset1{ 1, 3, 5, 7, 9, 11 };
setiset2{ 1, 2, 3, 4, 5, 6, 8, 10 };
setsame;
auto p1 = iset1.begin();
auto p2 = iset2.begin();
auto ps = same.begin();
if (!iset1.size () || !iset2.size ()) { cerr << "empty set exist!" << endl; return -1; }
for (size_t i = 0; i < iset1.size () && i < iset2.size (); ++i) {
if (*p1 > *p2)++p2;
else if (*p1 < *p2)++p1;
else { same.insert(*p1) ; ++p1; ++p2; }
}
copy(same.begin(), same.end(), ostream_iterator(cout, " "));
cout << endl;
return 0;
}