转自:http://blog.csdn.net/beyond_cn/article/details/9981561
<span style="font-family: 'Microsoft YaHei';">问:两个数组f[] g[] 长度不定 <span style="background-color: rgb(255, 255, 0);">元素从大到小排列好了</span> 每个数组中元素各不相同 请问如何编程能求两个数组相同元素个数 例如f[4]={1,3,4,7} g[5]={2,3,5,7,8} 有2个相同返回2 并求时间复杂度 最好时间复杂度小点 就是运算次数越少越好</span>
<pre id="best-content-390408182" class="best-text mb-10" name="code" style="white-space: pre-wrap; word-wrap: break-word; margin-top: 0px; margin-bottom: 10px; padding: 0px; background-color: rgb(241, 254, 221);"><span style="font-family: 'Microsoft YaHei';">答:</span>
<span style="font-family: 'Microsoft YaHei';">#include <conio.h> int Match2Array(const int * pArray1 , int iSize1 , const int * pArray2 , int iSize2 ) { const int * piFirEnd = pArray1+iSize1 , *piSecEnd = pArray2+iSize2; int iRet = 0; while ( pArray1 < piFirEnd && pArray2 < piSecEnd ) { if ( *pArray1 == *pArray2) { printf("%d ", *pArray1); pArray1++; pArray2++; iRet++; } else if ( *pArray1 < *pArray2 ) { pArray1++; } else { pArray2++; } } return iRet; }</span>
<span style="font-family: 'Microsoft YaHei';">时间复杂度o(m+n),m,n分别为两个数组大小.即最大比较次数为两个数组大小之和. 假如当前位置两个相等,则加1,元素互不相同,且有序,则第二个数组中不会再有其他数和第一个数组中当前数相同,故第一个数组当前位置加1,同理,第二个数组当前位置加1. 假如第一个数组元素小于第二个数组元素(*pArray1 < *pArray2 ),数组二中不会再有元素等于*pArray1,但是数组一可能还有元素等于*pArray2 。故pArray1++。 第一个数组元素大于第二个数组元素(*pArray1 < *pArray2 ),同理于第二种情况。</span>