1.4.11为StaticSETofInts添加一个实列方法howMany()(请见表1.2.15),找出给定键的出现次数且在最坏情况下所需的运行时间应该和logN成正比。
答:
import java.util.Arrays;
public class StaticSETofInts
{
private int[] a;
public StaticSETofInts(int[] keys)
{
a=new int[keys.length];
for (int i=0;i<keys.length;i++)
a[i]=keys[i];
Arrays.sort(a);
}
//
public boolean contains(int key)
{return BinarySearch.rank(key,a)!=-1;}
public int howMany(int key)
{
int maxIndex=BinarySearch.rankMax(key,a);
if (maxIndex==-1)
return 0;
else
return 1+maxIndex-BinarySearch.rankMin(key,a);
}
public static void main(String[] args)
{
int[] w=In.readInts(args[0]);
int key=Integer.parseInt(args[1]);
StaticSETofInts set=new StaticSETofInts(w);
StdOut.printf("contains key:%d %d pieces",key,set.howMany(key));
}
}
答:
import java.util.Arrays;
public class StaticSETofInts
{
private int[] a;
public StaticSETofInts(int[] keys)
{
a=new int[keys.length];
for (int i=0;i<keys.length;i++)
a[i]=keys[i];
Arrays.sort(a);
}
//
public boolean contains(int key)
{return BinarySearch.rank(key,a)!=-1;}
public int howMany(int key)
{
int maxIndex=BinarySearch.rankMax(key,a);
if (maxIndex==-1)
return 0;
else
return 1+maxIndex-BinarySearch.rankMin(key,a);
}
public static void main(String[] args)
{
int[] w=In.readInts(args[0]);
int key=Integer.parseInt(args[1]);
StaticSETofInts set=new StaticSETofInts(w);
StdOut.printf("contains key:%d %d pieces",key,set.howMany(key));
}
}