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

  • 相关阅读:
    JSON的序列化与还原
    正则表达式的一些基础
    跨域二三事
    与Web服务器通信
    与 Web 服务器通信
    代码重构
    构造函数与各种继承方法特点
    this指向问题——严格、非严格模式,事件处理程序
    《JavaScript设计模式与开发实践》学习笔记——单例模式
    Git常用命名及常见操作流程
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854406.html
Copyright © 2011-2022 走看看