Algs4-1.4.14 4-sum

1.4.14  4-sum。为4-sum设计一个算法。
答:
import java.util.Arrays;
public class FourSum
{
    public static int count1(int[] a)
    {
        int cnt=0;
        for(int i=0;i<a.length;i++)
            for(int j=i+1;j<a.length;j++)
                for(int k=j+1;k<a.length;k++)
                    for(int l=k+1;l<a.length;l++)
                        if(a[i]+a[j]+a[k]+a[l]==0)
                           cnt++;
        return cnt;
    }
   
    public static int count2(int[] a)
    {
       int cnt=0;
        Arrays.sort(a);
       for(int i=0;i<a.length;i++)
          for(int j=i+1;j<a.length;j++)
             for(int k=j+1;k<a.length;k++)
                if (BinarySearch.rank(-a[i]-a[j]-a[k],a)>k)
                      cnt++;
        return cnt;
    }
   
    public static int count3(int[] a)
    {
        int k;
        int l;
        int cnt=0;
        int sum;
        Arrays.sort(a);
        for(int i=0;i<a.length;i++)
            for (int j=i+1;j<a.length;j++)
               {
                  k=j+1;
                  l=a.length-1;
                  while(k<l)
                 {
                    sum=a[i]+a[j]+a[k]+a[l];
                    if(sum==0)
                    {
                      k++;
                      l--;
                      cnt++;
                    }
                else if(sum>0)
                    l--;
                else
                    k++;
            }//end while
        }//end for
        return cnt;
    }//end count
   
    public static void main(String[] args)
    {
        int[] a=In.readInts(args[0]);
        StdOut.println(count1(a));
        StdOut.println(count2(a));
        StdOut.println(count3(a));
    }
}

posted @ 2018-10-26 09:07  修电脑的龙生  阅读(254)  评论(0编辑  收藏  举报