码迷,mamicode.com
首页 > 其他好文 > 详细

1.4.11

时间:2018-06-03 14:50:12      阅读:142      评论:0      收藏:0      [点我收藏+]

标签: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);
    }
}

 

1.4.11

标签:while   answer   ==   min   nts   time   else   The   static   

原文地址:https://www.cnblogs.com/w-j-c/p/9128844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!