=================================版权声明=================================
版权声明:本文为博主原创文章 未经许可不得转载
请通过右侧公告中的“联系邮箱(wlsandwho@foxmail.com)”联系我
未经作者授权勿用于学术性引用。
未经作者授权勿用于商业出版、商业印刷、商业引用以及其他商业用途。
本文不定期修正完善,为保证内容正确,建议移步原文处阅读。 <--------总有一天我要自己做一个模板干掉这只土豆
本文链接:
耻辱墙:http://www.cnblogs.com/wlsandwho/p/4206472.html
=======================================================================
让我们先来回顾下小学公式
a+b=c
a=c-b b=c-a
a+b=b+a
回顾完毕
可以看代码了
1 #include <iostream> 2 3 using namespace std; 4 5 int BinarySearchByWLS(int nArray[],int nLen,int nDes) 6 { 7 int nIndex=-1; 8 9 int nLeft=0; 10 int nRight=nLen-1; 11 12 while(nLeft<=nRight) 13 { 14 nIndex=(nLeft+nRight)/2; 15 if (nArray[nIndex]==nDes) 16 { 17 return nIndex; 18 } 19 else 20 if (nArray[nIndex]<nDes) 21 { 22 nLeft=nIndex+1; 23 } 24 else 25 if (nArray[nIndex]>nDes) 26 { 27 nRight=nIndex-1; 28 } 29 } 30 31 return -1; 32 } 33 34 int FindAdditionFactorByWLS(int nArray[],int nLen,int nDes) 35 { 36 int nCounter=0; 37 38 int nIndex=0; 39 int nOtherFactor=0; 40 int nOtherFactorIndex=-1; 41 42 while (nIndex<nLen) 43 { 44 nOtherFactor=nDes-nArray[nIndex]; 45 nOtherFactorIndex=BinarySearchByWLS(nArray,nLen,nOtherFactor); 46 if (nOtherFactorIndex!=-1) 47 { 48 if (nOtherFactorIndex==nIndex) 49 { 50 nIndex++; 51 52 continue; 53 } 54 55 cout<<nDes<<"="<<nArray[nIndex]<<"+"<<nOtherFactor<<endl; 56 57 nCounter++; 58 } 59 60 nIndex++; 61 } 62 63 return nCounter; 64 } 65 66 int main() 67 { 68 int nArray[]={0,11,12,13,14,15,16,17,18,19}; 69 int nCounter=0; 70 nCounter=FindAdditionFactorByWLS(nArray,10,33); 71 cout<<"nCounter="<<nCounter<<endl; 72 73 return 0; 74 }
这段代码没有考虑a+b=b+a的情况
对于这种重复,个人感觉还是在结果集出来之后再过滤的好。