标签:while answer == min nts time else The static
question:
Add an instance method howMany() to StaticSETofInts(page 99) that finds the number of occurences of a given key in time proportional to logN in the worst case.
answer:
//和上一题1.4.10相关
import edu.princeton.cs.algs4.*; 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 Rank(key,a,0,a.length-1) != -1; } public int Rank(int key, int[]a, int lo, int hi)//用上题自己写的Rank { if(lo > hi) return -1; int mid = lo + (hi - lo)/2; if(a[mid] == key) { int min = Rank(key, a, lo, mid-1); if(min != -1) return min; return mid; } else if(a[mid] > key) return Rank(key, a, lo, mid-1); else return Rank(key, a, mid+1, hi); } public int howMany(int key) { int count = 0; int c = Rank(key,a,0,a.length); if(-1 == c) return 0; while(a[c] == key) { count++; c++; } return count; } public static void main(String[] args) { int[] c = {1,3,2,4,6,8,1,5,2,6,8,9,3,3,2,1,1};//四个1 StaticSETofInts staticsetofints = new StaticSETofInts(c); int count = staticsetofints.howMany(1); StdOut.println(count); } }
标签:while answer == min nts time else The static
原文地址:https://www.cnblogs.com/w-j-c/p/9128844.html