zoukankan      html  css  js  c++  java
  • Algs4-1.2.9使用Counter统计BinarySearch检查的key个数

    1.2.9修改BinarySearch(请见1.1.10.1节中的二分查找代码),使用Counter统计在有查找中被检查的键的总数并在查找全部结束后打印该值。提示:在main()中创建一个Counter对象并将它作为参数传递给rank()。
    答:
    图片
    BinarySearch Code:
    import java.util.Arrays;

    public class Test
    {
      public static void main(String[] args) 
      {
        int[] whitelist=In.readInts(args[0]);
        Arrays.sort(whitelist);
        Counter counterKey=new Counter("counterKey");
        while (!StdIn.isEmpty())
        {
            int key=StdIn.readInt();
            int indexOfWhite=rank(key,whitelist,counterKey);
        }
         StdOut.printf("BinarySearch check Key Counter is:%d ",counterKey.tally());
        }//end main
     
      public static int rank(int key,int[] a,Counter counterKey)
      {
          int lo=0;
          int hi=a.length-1;
          while(lo<=hi)
          {
              counterKey.increment();
              int mid=lo+(hi-lo)/2;
              if (key<a[mid]) hi=mid-1;
              else if(key>a[mid]) lo=mid+1;
              else return mid;
          }
          return -1;
      }
    }//end class Test


    ////////////////////////////////////
    Counter Code:
    public class Counter
    {
        private final String name;
        private int count;
        public Counter(String id)
        {
            name=id;
            count=0;
        }  
       
        public void increment()
        {
            count++;
        }
       
        public int tally()
        {
            return count;
        }
       
        public String ToString()
        {
            return count+ " " +name;
        }
       
        public static void main(String[] args)
        {
            Counter heads=new Counter("heads");
            Counter tails=new Counter("tails");
           
            heads.increment();
            heads.increment();
            tails.increment();
           
            StdOut.println(heads+" " + tails);
            StdOut.println(heads.tally() + tails.tally());
           
        }
    }
  • 相关阅读:
    Leetcode665.Non-decreasing Array非递减数组
    在MyEclipse中把多行代码用一快捷键注释掉
    struts2中addFieldError()方法
    [bzoj2588][Spoj10628]Count on a tree_主席树
    [bzoj3123][Sdoi2013]森林_主席树_启发式合并
    [bzoj1500][NOI2005]维修数列_非旋转Treap
    [bzoj1452][JSOI2009]Count_树状数组
    [bzoj1369][Baltic2003]Gem_树形dp_结论题
    [bzoj1195][HNOI2006]最短母串_动态规划_状压dp
    [bzoj2242][Sdoi2011]计算器_exgcd_BSGS
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9848850.html
Copyright © 2011-2022 走看看