int[] a = new int[m]; int[] b = new int[n]; ArrayList andData = new ArrayList(); //a与b的初始化 int j = 0; for(int i = 0;i < m;i++) { do { if(a[i] == b[j]) { andData.Add(a[i]); break; } j++; }while(j < n && a[i] != b[j]) } return andData;
1. add 1,3,5,6,7,9 to hash table, key and value use the same value. 2.foreach(int key in 2,4,6,7,8,9) { if(hashtbl[key]!=null) { hashtbl[key] ----is the data you want. } }
放两个List里,表面效率为O(n); List<int> lst1 = new List<int>() { 1, 3, 5, 6, 7, 9 }; List<int> lst2 = new List<int>() { 2, 4, 6, 7, 8, 9 }; for (int i = 0; i < lst1.Count; i++) { if (lst2.Contains(lst1[i])) { Console.WriteLine(lst1[i]); } }
那么将数组a中数据全部插入数组b,从b里边找有重复的项就可以这算法写起来可能比较简单,但实际上时间复杂度可能还不如循环比较-_-
int[] b = new int[n];
ArrayList andData = new ArrayList();
//a与b的初始化
int j = 0;
for(int i = 0;i < m;i++)
{
do
{
if(a[i] == b[j])
{
andData.Add(a[i]);
break;
}
j++;
}while(j < n && a[i] != b[j])
}
return andData;
2.foreach(int key in 2,4,6,7,8,9) {
if(hashtbl[key]!=null)
{
hashtbl[key] ----is the data you want.
}
}
List<int> lst2 = new List<int>() { 2, 4, 6, 7, 8, 9 };
for (int i = 0; i < lst1.Count; i++)
{
if (lst2.Contains(lst1[i]))
{
Console.WriteLine(lst1[i]);
}
}
int[] A=new []{1,2,3,4,5};
int[] B=new []{2,4,9,10}; int[] C=A.Intersect(B).ToArray();
int[] A=new []{1,2,3,4,5};
int[] B=new []{2,4,9,10};
int i,j;
i=0;
j=0;
while(true)
{
if(i>=A.Length)
break;
if(j>=B.Length)
break;
if(A[i]>B[j])
j++;
if((A[i]<B[j])
i++;
if((A[i]=B[j])
{
Console.WriteLine(A[i]);
i++;
j++;
}
}
int[] A=new []{1,3,5,6,7,9 };
int[] B=new []{2,4,6,7,8,9};
int i,j;
i=0;
j=0;
while(true)
{
if(i>=A.Length)
break;
if(j>=B.Length)
break;
if((A[i]=B[j])
{
Console.WriteLine(A[i]);
i++;
j++;
}
if(A[i]>B[j])
j++;
if((A[i]<B[j])
i++;
}
改正一些错误和重新格式了一下: int[] A = { 1, 3, 5, 6, 7, 9 };
int[] B = { 2, 4, 6, 7, 8, 9 }; int i = 0, j = 0;
while ( i<A.Length && j < B.Length )
{
if (A[i] == B[j])
{
Console.WriteLine(A[i]);
i++;
j++;
}
else if (A[i] > B[j]) j++;
else if (A[i] < B[j]) i++;
}
6楼 O(N*LogM)
7楼 O(N*M)
11楼 O(M),可能退化,空间复杂度高
12楼 O(N*M)
15楼 O(M),内部用哈什,同样可能退化,空间复杂度高hash table的优势在于不要求数据事先排序,在数据已经排序的情况下,它(算法上)不是最优。
另外一点,hash table方式适用于集合(集合元素不重复),比如对下面的排序数据,15楼返回{2,9},20楼返回{2,2,9}:
int[] A= {2,2,3,4,9};
int[] B= {2,2,9,10};