1.4.21无重复值之中的二分查找。用二分查找实现StaticSETofInts(请见表1.2.15),保证contains()的运行时间为~lgR,其中R为参数数组中不同整数的数量。
答:感觉到不到点。
import java.util.Arrays;
public class E1d4d21
{
private int[] a;
public E1d4d21(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)
{
int lo=0;
int hi=a.length-1;
while (lo<=hi)
{
int mid=lo+(hi-lo)/2;
if (key<a[mid]) hi=mid-1;
else if(key>a[mid]) lo=mid+1;
else return true;
}
return false;
}
public static void main(String[] args)
{
int[] w=In.readInts(args[0]);
int key=Integer.parseInt(args[1]);
E1d4d21 set=new E1d4d21(w);
StdOut.printf("contains key:%d is %s",key,set.contains(key));
}
}