3sum问题

参考:http://en.wikipedia.org/wiki/3SUM

//choose three number from a set,then a+b+c=0

View Code
//choose three number from a set,then a+b+c=0
//其实就是两头逼近,复杂度O(N^2)
void threesum(int n,int*val) {
    int i,j,k,a,b,c,tmp,l;
    sort(val,val+n);
    for(i=0;i<n-2;i++) {
        a=val[i], j=i+1, k=n-1;
        while(j<k) {
            b=val[j], c=val[k], tmp=a+b+c;
            if(tmp==0) {
                printf("%d %d %d\n",a,b,c);
                return;
            }
            else if(tmp>0) k--;
            else j++;
        }
    }
    puts("no solution");
}

 

posted @ 2013-05-02 20:55  zhang1107  阅读(143)  评论(0编辑  收藏  举报