Algs4-1.4.8计算输入文件中相等的整数对的数量

1.4.8编写一个程序,计算输入文件中相等的整数对的数量。如果你的第一个程序是平方级别的,请继续思考并用Array.sort()给出一个线性对数级别的解答。
import java.util.Arrays;
public class TwoSame
{
 //增长函数N2 
public static int count1(int[] a)
    {
        int N=a.length;
        int cnt=0;
        for (int i=0;i<N;i++)
            for (int j=i+1;j<N;j++)
                     if(a[i]==a[j])
                        cnt++;
        return cnt;
    }
 //增长函数NlgN,最坏情况所有数都相等时 N2
 

     public static int count2(int[] a)
    {
        int N=a.length;
        int cnt=0;
        Arrays.sort(a);
        for (int i=0;i<N;i++)
             for(int j=i+1;j<N && a[i]==a[j];j++)
                        cnt++;//调整此处的代码可以滑过相等项,对于所有数相同时增长函数为NlgN
        return cnt;
    }
   
    public static void main(String[] args)
    {
        int[] a=In.readInts(args[0]);
        StdOut.println("count1="+count1(a));
        StdOut.println("count2="+count2(a));
    }
}

原文地址:https://www.cnblogs.com/longjin2018/p/9854406.html