zoukankan      html  css  js  c++  java
  • 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));
        }
    }

  • 相关阅读:
    January 25th, 2018 Week 04th Thursday
    January 24th, 2018 Week 04th Wednesday
    January 23rd, 2018 Week 04th Tuesday
    January 22nd, 2018 Week 04th Monday
    January 21st, 2018 Week 3rd Sunday
    January 20th, 2018 Week 3rd Saturday
    January 19th, 2018 Week 3rd Friday
    January 18th, 2018 Week 03rd Thursday
    January 17th, 2018 Week 03rd Wednesday
    January 16th, 2018 Week 03rd Tuesday
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854424.html
Copyright © 2011-2022 走看看